LCOV - code coverage report
Current view: top level - src/backend/storage/lmgr - lock.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 87.8 % 1282 1126
Test Date: 2026-08-16 15:16:46 Functions: 96.7 % 61 59
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 64.9 % 906 588

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * lock.c
       4                 :             :  *    POSTGRES primary lock mechanism
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  *
      10                 :             :  * IDENTIFICATION
      11                 :             :  *    src/backend/storage/lmgr/lock.c
      12                 :             :  *
      13                 :             :  * NOTES
      14                 :             :  *    A lock table is a shared memory hash table.  When
      15                 :             :  *    a process tries to acquire a lock of a type that conflicts
      16                 :             :  *    with existing locks, it is put to sleep using the routines
      17                 :             :  *    in storage/lmgr/proc.c.
      18                 :             :  *
      19                 :             :  *    For the most part, this code should be invoked via lmgr.c
      20                 :             :  *    or another lock-management module, not directly.
      21                 :             :  *
      22                 :             :  *  Interface:
      23                 :             :  *
      24                 :             :  *  LockManagerShmemInit(), GetLocksMethodTable(), GetLockTagsMethodTable(),
      25                 :             :  *  LockAcquire(), LockRelease(), LockReleaseAll(),
      26                 :             :  *  LockCheckConflicts(), GrantLock()
      27                 :             :  *
      28                 :             :  *-------------------------------------------------------------------------
      29                 :             :  */
      30                 :             : #include "postgres.h"
      31                 :             : 
      32                 :             : #include <signal.h>
      33                 :             : #include <unistd.h>
      34                 :             : 
      35                 :             : #include "access/transam.h"
      36                 :             : #include "access/twophase.h"
      37                 :             : #include "access/twophase_rmgr.h"
      38                 :             : #include "access/xlog.h"
      39                 :             : #include "access/xlogutils.h"
      40                 :             : #include "miscadmin.h"
      41                 :             : #include "pg_trace.h"
      42                 :             : #include "pgstat.h"
      43                 :             : #include "storage/lmgr.h"
      44                 :             : #include "storage/proc.h"
      45                 :             : #include "storage/procarray.h"
      46                 :             : #include "storage/shmem.h"
      47                 :             : #include "storage/spin.h"
      48                 :             : #include "storage/standby.h"
      49                 :             : #include "storage/subsystems.h"
      50                 :             : #include "utils/memutils.h"
      51                 :             : #include "utils/ps_status.h"
      52                 :             : #include "utils/resowner.h"
      53                 :             : 
      54                 :             : 
      55                 :             : /* GUC variables */
      56                 :             : int         max_locks_per_xact; /* used to set the lock table size */
      57                 :             : bool        log_lock_failures = false;
      58                 :             : 
      59                 :             : #define NLOCKENTS() \
      60                 :             :     mul_size(max_locks_per_xact, add_size(MaxBackends, max_prepared_xacts))
      61                 :             : 
      62                 :             : 
      63                 :             : /*
      64                 :             :  * Data structures defining the semantics of the standard lock methods.
      65                 :             :  *
      66                 :             :  * The conflict table defines the semantics of the various lock modes.
      67                 :             :  */
      68                 :             : static const LOCKMASK LockConflicts[] = {
      69                 :             :     0,
      70                 :             : 
      71                 :             :     /* AccessShareLock */
      72                 :             :     LOCKBIT_ON(AccessExclusiveLock),
      73                 :             : 
      74                 :             :     /* RowShareLock */
      75                 :             :     LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
      76                 :             : 
      77                 :             :     /* RowExclusiveLock */
      78                 :             :     LOCKBIT_ON(ShareLock) | LOCKBIT_ON(ShareRowExclusiveLock) |
      79                 :             :     LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
      80                 :             : 
      81                 :             :     /* ShareUpdateExclusiveLock */
      82                 :             :     LOCKBIT_ON(ShareUpdateExclusiveLock) |
      83                 :             :     LOCKBIT_ON(ShareLock) | LOCKBIT_ON(ShareRowExclusiveLock) |
      84                 :             :     LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
      85                 :             : 
      86                 :             :     /* ShareLock */
      87                 :             :     LOCKBIT_ON(RowExclusiveLock) | LOCKBIT_ON(ShareUpdateExclusiveLock) |
      88                 :             :     LOCKBIT_ON(ShareRowExclusiveLock) |
      89                 :             :     LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
      90                 :             : 
      91                 :             :     /* ShareRowExclusiveLock */
      92                 :             :     LOCKBIT_ON(RowExclusiveLock) | LOCKBIT_ON(ShareUpdateExclusiveLock) |
      93                 :             :     LOCKBIT_ON(ShareLock) | LOCKBIT_ON(ShareRowExclusiveLock) |
      94                 :             :     LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
      95                 :             : 
      96                 :             :     /* ExclusiveLock */
      97                 :             :     LOCKBIT_ON(RowShareLock) |
      98                 :             :     LOCKBIT_ON(RowExclusiveLock) | LOCKBIT_ON(ShareUpdateExclusiveLock) |
      99                 :             :     LOCKBIT_ON(ShareLock) | LOCKBIT_ON(ShareRowExclusiveLock) |
     100                 :             :     LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
     101                 :             : 
     102                 :             :     /* AccessExclusiveLock */
     103                 :             :     LOCKBIT_ON(AccessShareLock) | LOCKBIT_ON(RowShareLock) |
     104                 :             :     LOCKBIT_ON(RowExclusiveLock) | LOCKBIT_ON(ShareUpdateExclusiveLock) |
     105                 :             :     LOCKBIT_ON(ShareLock) | LOCKBIT_ON(ShareRowExclusiveLock) |
     106                 :             :     LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock)
     107                 :             : 
     108                 :             : };
     109                 :             : 
     110                 :             : /* Names of lock modes, for debug printouts */
     111                 :             : static const char *const lock_mode_names[] =
     112                 :             : {
     113                 :             :     "INVALID",
     114                 :             :     "AccessShareLock",
     115                 :             :     "RowShareLock",
     116                 :             :     "RowExclusiveLock",
     117                 :             :     "ShareUpdateExclusiveLock",
     118                 :             :     "ShareLock",
     119                 :             :     "ShareRowExclusiveLock",
     120                 :             :     "ExclusiveLock",
     121                 :             :     "AccessExclusiveLock"
     122                 :             : };
     123                 :             : 
     124                 :             : #ifndef LOCK_DEBUG
     125                 :             : static bool Dummy_trace = false;
     126                 :             : #endif
     127                 :             : 
     128                 :             : static const LockMethodData default_lockmethod = {
     129                 :             :     MaxLockMode,
     130                 :             :     LockConflicts,
     131                 :             :     lock_mode_names,
     132                 :             : #ifdef LOCK_DEBUG
     133                 :             :     &Trace_locks
     134                 :             : #else
     135                 :             :     &Dummy_trace
     136                 :             : #endif
     137                 :             : };
     138                 :             : 
     139                 :             : static const LockMethodData user_lockmethod = {
     140                 :             :     MaxLockMode,
     141                 :             :     LockConflicts,
     142                 :             :     lock_mode_names,
     143                 :             : #ifdef LOCK_DEBUG
     144                 :             :     &Trace_userlocks
     145                 :             : #else
     146                 :             :     &Dummy_trace
     147                 :             : #endif
     148                 :             : };
     149                 :             : 
     150                 :             : /*
     151                 :             :  * map from lock method id to the lock table data structures
     152                 :             :  */
     153                 :             : static const LockMethod LockMethods[] = {
     154                 :             :     NULL,
     155                 :             :     &default_lockmethod,
     156                 :             :     &user_lockmethod
     157                 :             : };
     158                 :             : 
     159                 :             : 
     160                 :             : /* Record that's written to 2PC state file when a lock is persisted */
     161                 :             : typedef struct TwoPhaseLockRecord
     162                 :             : {
     163                 :             :     LOCKTAG     locktag;
     164                 :             :     LOCKMODE    lockmode;
     165                 :             : } TwoPhaseLockRecord;
     166                 :             : 
     167                 :             : 
     168                 :             : /*
     169                 :             :  * Count of the number of fast path lock slots we believe to be used.  This
     170                 :             :  * might be higher than the real number if another backend has transferred
     171                 :             :  * our locks to the primary lock table, but it can never be lower than the
     172                 :             :  * real value, since only we can acquire locks on our own behalf.
     173                 :             :  *
     174                 :             :  * XXX Allocate a static array of the maximum size. We could use a pointer
     175                 :             :  * and then allocate just the right size to save a couple kB, but then we
     176                 :             :  * would have to initialize that, while for the static array that happens
     177                 :             :  * automatically. Doesn't seem worth the extra complexity.
     178                 :             :  */
     179                 :             : static int  FastPathLocalUseCounts[FP_LOCK_GROUPS_PER_BACKEND_MAX];
     180                 :             : 
     181                 :             : /*
     182                 :             :  * Flag to indicate if the relation extension lock is held by this backend.
     183                 :             :  * This flag is used to ensure that while holding the relation extension lock
     184                 :             :  * we don't try to acquire a heavyweight lock on any other object.  This
     185                 :             :  * restriction implies that the relation extension lock won't ever participate
     186                 :             :  * in the deadlock cycle because we can never wait for any other heavyweight
     187                 :             :  * lock after acquiring this lock.
     188                 :             :  *
     189                 :             :  * Such a restriction is okay for relation extension locks as unlike other
     190                 :             :  * heavyweight locks these are not held till the transaction end.  These are
     191                 :             :  * taken for a short duration to extend a particular relation and then
     192                 :             :  * released.
     193                 :             :  */
     194                 :             : static bool IsRelationExtensionLockHeld PG_USED_FOR_ASSERTS_ONLY = false;
     195                 :             : 
     196                 :             : /*
     197                 :             :  * Number of fast-path locks per backend - size of the arrays in PGPROC.
     198                 :             :  * This is set only once during start, before initializing shared memory,
     199                 :             :  * and remains constant after that.
     200                 :             :  *
     201                 :             :  * We set the limit based on max_locks_per_transaction GUC, because that's
     202                 :             :  * the best information about expected number of locks per backend we have.
     203                 :             :  * See InitializeFastPathLocks() for details.
     204                 :             :  */
     205                 :             : int         FastPathLockGroupsPerBackend = 0;
     206                 :             : 
     207                 :             : /*
     208                 :             :  * Macros to calculate the fast-path group and index for a relation.
     209                 :             :  *
     210                 :             :  * The formula is a simple hash function, designed to spread the OIDs a bit,
     211                 :             :  * so that even contiguous values end up in different groups. In most cases
     212                 :             :  * there will be gaps anyway, but the multiplication should help a bit.
     213                 :             :  *
     214                 :             :  * The selected constant (49157) is a prime not too close to 2^k, and it's
     215                 :             :  * small enough to not cause overflows (in 64-bit).
     216                 :             :  *
     217                 :             :  * We can assume that FastPathLockGroupsPerBackend is a power-of-two per
     218                 :             :  * InitializeFastPathLocks().
     219                 :             :  */
     220                 :             : #define FAST_PATH_REL_GROUP(rel) \
     221                 :             :     (((uint64) (rel) * 49157) & (FastPathLockGroupsPerBackend - 1))
     222                 :             : 
     223                 :             : /*
     224                 :             :  * Given the group/slot indexes, calculate the slot index in the whole array
     225                 :             :  * of fast-path lock slots.
     226                 :             :  */
     227                 :             : #define FAST_PATH_SLOT(group, index) \
     228                 :             :     (AssertMacro((uint32) (group) < FastPathLockGroupsPerBackend), \
     229                 :             :      AssertMacro((uint32) (index) < FP_LOCK_SLOTS_PER_GROUP), \
     230                 :             :      ((group) * FP_LOCK_SLOTS_PER_GROUP + (index)))
     231                 :             : 
     232                 :             : /*
     233                 :             :  * Given a slot index (into the whole per-backend array), calculated using
     234                 :             :  * the FAST_PATH_SLOT macro, split it into group and index (in the group).
     235                 :             :  */
     236                 :             : #define FAST_PATH_GROUP(index)  \
     237                 :             :     (AssertMacro((uint32) (index) < FastPathLockSlotsPerBackend()), \
     238                 :             :      ((index) / FP_LOCK_SLOTS_PER_GROUP))
     239                 :             : #define FAST_PATH_INDEX(index)  \
     240                 :             :     (AssertMacro((uint32) (index) < FastPathLockSlotsPerBackend()), \
     241                 :             :      ((index) % FP_LOCK_SLOTS_PER_GROUP))
     242                 :             : 
     243                 :             : /* Macros for manipulating proc->fpLockBits */
     244                 :             : #define FAST_PATH_BITS_PER_SLOT         3
     245                 :             : #define FAST_PATH_LOCKNUMBER_OFFSET     1
     246                 :             : #define FAST_PATH_MASK                  ((1 << FAST_PATH_BITS_PER_SLOT) - 1)
     247                 :             : #define FAST_PATH_BITS(proc, n)         (proc)->fpLockBits[FAST_PATH_GROUP(n)]
     248                 :             : #define FAST_PATH_GET_BITS(proc, n) \
     249                 :             :     ((FAST_PATH_BITS(proc, n) >> (FAST_PATH_BITS_PER_SLOT * FAST_PATH_INDEX(n))) & FAST_PATH_MASK)
     250                 :             : #define FAST_PATH_BIT_POSITION(n, l) \
     251                 :             :     (AssertMacro((l) >= FAST_PATH_LOCKNUMBER_OFFSET), \
     252                 :             :      AssertMacro((l) < FAST_PATH_BITS_PER_SLOT+FAST_PATH_LOCKNUMBER_OFFSET), \
     253                 :             :      AssertMacro((n) < FastPathLockSlotsPerBackend()), \
     254                 :             :      ((l) - FAST_PATH_LOCKNUMBER_OFFSET + FAST_PATH_BITS_PER_SLOT * (FAST_PATH_INDEX(n))))
     255                 :             : #define FAST_PATH_SET_LOCKMODE(proc, n, l) \
     256                 :             :      FAST_PATH_BITS(proc, n) |= UINT64CONST(1) << FAST_PATH_BIT_POSITION(n, l)
     257                 :             : #define FAST_PATH_CLEAR_LOCKMODE(proc, n, l) \
     258                 :             :      FAST_PATH_BITS(proc, n) &= ~(UINT64CONST(1) << FAST_PATH_BIT_POSITION(n, l))
     259                 :             : #define FAST_PATH_CHECK_LOCKMODE(proc, n, l) \
     260                 :             :      (FAST_PATH_BITS(proc, n) & (UINT64CONST(1) << FAST_PATH_BIT_POSITION(n, l)))
     261                 :             : 
     262                 :             : /*
     263                 :             :  * The fast-path lock mechanism is concerned only with relation locks on
     264                 :             :  * unshared relations by backends bound to a database.  The fast-path
     265                 :             :  * mechanism exists mostly to accelerate acquisition and release of locks
     266                 :             :  * that rarely conflict.  Because ShareUpdateExclusiveLock is
     267                 :             :  * self-conflicting, it can't use the fast-path mechanism; but it also does
     268                 :             :  * not conflict with any of the locks that do, so we can ignore it completely.
     269                 :             :  */
     270                 :             : #define EligibleForRelationFastPath(locktag, mode) \
     271                 :             :     ((locktag)->locktag_lockmethodid == DEFAULT_LOCKMETHOD && \
     272                 :             :     (locktag)->locktag_type == LOCKTAG_RELATION && \
     273                 :             :     (locktag)->locktag_field1 == MyDatabaseId && \
     274                 :             :     MyDatabaseId != InvalidOid && \
     275                 :             :     (mode) < ShareUpdateExclusiveLock)
     276                 :             : #define ConflictsWithRelationFastPath(locktag, mode) \
     277                 :             :     ((locktag)->locktag_lockmethodid == DEFAULT_LOCKMETHOD && \
     278                 :             :     (locktag)->locktag_type == LOCKTAG_RELATION && \
     279                 :             :     (locktag)->locktag_field1 != InvalidOid && \
     280                 :             :     (mode) > ShareUpdateExclusiveLock)
     281                 :             : 
     282                 :             : static bool FastPathGrantRelationLock(Oid relid, LOCKMODE lockmode);
     283                 :             : static bool FastPathUnGrantRelationLock(Oid relid, LOCKMODE lockmode);
     284                 :             : static bool FastPathTransferRelationLocks(LockMethod lockMethodTable,
     285                 :             :                                           const LOCKTAG *locktag, uint32 hashcode);
     286                 :             : static PROCLOCK *FastPathGetRelationLockEntry(LOCALLOCK *locallock);
     287                 :             : 
     288                 :             : /*
     289                 :             :  * To make the fast-path lock mechanism work, we must have some way of
     290                 :             :  * preventing the use of the fast-path when a conflicting lock might be present.
     291                 :             :  * We partition* the locktag space into FAST_PATH_STRONG_LOCK_HASH_PARTITIONS,
     292                 :             :  * and maintain an integer count of the number of "strong" lockers
     293                 :             :  * in each partition.  When any "strong" lockers are present (which is
     294                 :             :  * hopefully not very often), the fast-path mechanism can't be used, and we
     295                 :             :  * must fall back to the slower method of pushing matching locks directly
     296                 :             :  * into the main lock tables.
     297                 :             :  *
     298                 :             :  * The deadlock detector does not know anything about the fast path mechanism,
     299                 :             :  * so any locks that might be involved in a deadlock must be transferred from
     300                 :             :  * the fast-path queues to the main lock table.
     301                 :             :  */
     302                 :             : 
     303                 :             : #define FAST_PATH_STRONG_LOCK_HASH_BITS         10
     304                 :             : #define FAST_PATH_STRONG_LOCK_HASH_PARTITIONS \
     305                 :             :     (1 << FAST_PATH_STRONG_LOCK_HASH_BITS)
     306                 :             : #define FastPathStrongLockHashPartition(hashcode) \
     307                 :             :     ((hashcode) % FAST_PATH_STRONG_LOCK_HASH_PARTITIONS)
     308                 :             : 
     309                 :             : typedef struct
     310                 :             : {
     311                 :             :     slock_t     mutex;
     312                 :             :     uint32      count[FAST_PATH_STRONG_LOCK_HASH_PARTITIONS];
     313                 :             : } FastPathStrongRelationLockData;
     314                 :             : 
     315                 :             : static FastPathStrongRelationLockData *FastPathStrongRelationLocks;
     316                 :             : 
     317                 :             : static void LockManagerShmemRequest(void *arg);
     318                 :             : static void LockManagerShmemInit(void *arg);
     319                 :             : 
     320                 :             : const ShmemCallbacks LockManagerShmemCallbacks = {
     321                 :             :     .request_fn = LockManagerShmemRequest,
     322                 :             :     .init_fn = LockManagerShmemInit,
     323                 :             : };
     324                 :             : 
     325                 :             : 
     326                 :             : /*
     327                 :             :  * Pointers to hash tables containing lock state
     328                 :             :  *
     329                 :             :  * The LockMethodLockHash and LockMethodProcLockHash hash tables are in
     330                 :             :  * shared memory; LockMethodLocalHash is local to each backend.
     331                 :             :  */
     332                 :             : static HTAB *LockMethodLockHash;
     333                 :             : static HTAB *LockMethodProcLockHash;
     334                 :             : static HTAB *LockMethodLocalHash;
     335                 :             : 
     336                 :             : 
     337                 :             : /* private state for error cleanup */
     338                 :             : static LOCALLOCK *StrongLockInProgress;
     339                 :             : static LOCALLOCK *awaitedLock;
     340                 :             : static ResourceOwner awaitedOwner;
     341                 :             : 
     342                 :             : 
     343                 :             : #ifdef LOCK_DEBUG
     344                 :             : 
     345                 :             : /*------
     346                 :             :  * The following configuration options are available for lock debugging:
     347                 :             :  *
     348                 :             :  *     TRACE_LOCKS      -- give a bunch of output what's going on in this file
     349                 :             :  *     TRACE_USERLOCKS  -- same but for user locks
     350                 :             :  *     TRACE_LOCK_OIDMIN-- do not trace locks for tables below this oid
     351                 :             :  *                         (use to avoid output on system tables)
     352                 :             :  *     TRACE_LOCK_TABLE -- trace locks on this table (oid) unconditionally
     353                 :             :  *     DEBUG_DEADLOCKS  -- currently dumps locks at untimely occasions ;)
     354                 :             :  *
     355                 :             :  * Furthermore, but in storage/lmgr/lwlock.c:
     356                 :             :  *     TRACE_LWLOCKS    -- trace lightweight locks (pretty useless)
     357                 :             :  *
     358                 :             :  * Define LOCK_DEBUG at compile time to get all these enabled.
     359                 :             :  * --------
     360                 :             :  */
     361                 :             : 
     362                 :             : int         Trace_lock_oidmin = FirstNormalObjectId;
     363                 :             : bool        Trace_locks = false;
     364                 :             : bool        Trace_userlocks = false;
     365                 :             : int         Trace_lock_table = 0;
     366                 :             : bool        Debug_deadlocks = false;
     367                 :             : 
     368                 :             : 
     369                 :             : inline static bool
     370                 :             : LOCK_DEBUG_ENABLED(const LOCKTAG *tag)
     371                 :             : {
     372                 :             :     return
     373                 :             :         (*(LockMethods[tag->locktag_lockmethodid]->trace_flag) &&
     374                 :             :          ((Oid) tag->locktag_field2 >= (Oid) Trace_lock_oidmin))
     375                 :             :         || (Trace_lock_table &&
     376                 :             :             (tag->locktag_field2 == Trace_lock_table));
     377                 :             : }
     378                 :             : 
     379                 :             : 
     380                 :             : inline static void
     381                 :             : LOCK_PRINT(const char *where, const LOCK *lock, LOCKMODE type)
     382                 :             : {
     383                 :             :     if (LOCK_DEBUG_ENABLED(&lock->tag))
     384                 :             :         elog(LOG,
     385                 :             :              "%s: lock(%p) id(%u,%u,%u,%u,%u,%u) grantMask(%x) "
     386                 :             :              "req(%d,%d,%d,%d,%d,%d,%d)=%d "
     387                 :             :              "grant(%d,%d,%d,%d,%d,%d,%d)=%d wait(%d) type(%s)",
     388                 :             :              where, lock,
     389                 :             :              lock->tag.locktag_field1, lock->tag.locktag_field2,
     390                 :             :              lock->tag.locktag_field3, lock->tag.locktag_field4,
     391                 :             :              lock->tag.locktag_type, lock->tag.locktag_lockmethodid,
     392                 :             :              lock->grantMask,
     393                 :             :              lock->requested[1], lock->requested[2], lock->requested[3],
     394                 :             :              lock->requested[4], lock->requested[5], lock->requested[6],
     395                 :             :              lock->requested[7], lock->nRequested,
     396                 :             :              lock->granted[1], lock->granted[2], lock->granted[3],
     397                 :             :              lock->granted[4], lock->granted[5], lock->granted[6],
     398                 :             :              lock->granted[7], lock->nGranted,
     399                 :             :              dclist_count(&lock->waitProcs),
     400                 :             :              LockMethods[LOCK_LOCKMETHOD(*lock)]->lockModeNames[type]);
     401                 :             : }
     402                 :             : 
     403                 :             : 
     404                 :             : inline static void
     405                 :             : PROCLOCK_PRINT(const char *where, const PROCLOCK *proclockP)
     406                 :             : {
     407                 :             :     if (LOCK_DEBUG_ENABLED(&proclockP->tag.myLock->tag))
     408                 :             :         elog(LOG,
     409                 :             :              "%s: proclock(%p) lock(%p) method(%u) proc(%p) hold(%x)",
     410                 :             :              where, proclockP, proclockP->tag.myLock,
     411                 :             :              PROCLOCK_LOCKMETHOD(*(proclockP)),
     412                 :             :              proclockP->tag.myProc, (int) proclockP->holdMask);
     413                 :             : }
     414                 :             : #else                           /* not LOCK_DEBUG */
     415                 :             : 
     416                 :             : #define LOCK_PRINT(where, lock, type)  ((void) 0)
     417                 :             : #define PROCLOCK_PRINT(where, proclockP)  ((void) 0)
     418                 :             : #endif                          /* not LOCK_DEBUG */
     419                 :             : 
     420                 :             : 
     421                 :             : static uint32 proclock_hash(const void *key, Size keysize);
     422                 :             : static void RemoveLocalLock(LOCALLOCK *locallock);
     423                 :             : static PROCLOCK *SetupLockInTable(LockMethod lockMethodTable, PGPROC *proc,
     424                 :             :                                   const LOCKTAG *locktag, uint32 hashcode, LOCKMODE lockmode);
     425                 :             : static void GrantLockLocal(LOCALLOCK *locallock, ResourceOwner owner);
     426                 :             : static void BeginStrongLockAcquire(LOCALLOCK *locallock, uint32 fasthashcode);
     427                 :             : static void FinishStrongLockAcquire(void);
     428                 :             : static ProcWaitStatus WaitOnLock(LOCALLOCK *locallock, ResourceOwner owner);
     429                 :             : static void waitonlock_error_callback(void *arg);
     430                 :             : static void ReleaseLockIfHeld(LOCALLOCK *locallock, bool sessionLock);
     431                 :             : static void LockReassignOwner(LOCALLOCK *locallock, ResourceOwner parent);
     432                 :             : static bool UnGrantLock(LOCK *lock, LOCKMODE lockmode,
     433                 :             :                         PROCLOCK *proclock, LockMethod lockMethodTable);
     434                 :             : static void CleanUpLock(LOCK *lock, PROCLOCK *proclock,
     435                 :             :                         LockMethod lockMethodTable, uint32 hashcode,
     436                 :             :                         bool wakeupNeeded);
     437                 :             : static void LockRefindAndRelease(LockMethod lockMethodTable, PGPROC *proc,
     438                 :             :                                  LOCKTAG *locktag, LOCKMODE lockmode,
     439                 :             :                                  bool decrement_strong_lock_count);
     440                 :             : static void GetSingleProcBlockerStatusData(PGPROC *blocked_proc,
     441                 :             :                                            BlockedProcsData *data);
     442                 :             : 
     443                 :             : 
     444                 :             : /*
     445                 :             :  * Register the lock manager's shmem data structures.
     446                 :             :  *
     447                 :             :  * In addition to this, each backend must also call InitLockManagerAccess() to
     448                 :             :  * create the locallock hash table.
     449                 :             :  */
     450                 :             : static void
     451                 :        1271 : LockManagerShmemRequest(void *arg)
     452                 :             : {
     453                 :             :     int64       max_table_size;
     454                 :             : 
     455                 :             :     /*
     456                 :             :      * Compute sizes for lock hashtables.
     457                 :             :      */
     458                 :        1271 :     max_table_size = NLOCKENTS();
     459                 :             : 
     460                 :             :     /*
     461                 :             :      * Hash table for LOCK structs.  This stores per-locked-object
     462                 :             :      * information.
     463                 :             :      */
     464                 :        1271 :     ShmemRequestHash(.name = "LOCK hash",
     465                 :             :                      .nelems = max_table_size,
     466                 :             :                      .ptr = &LockMethodLockHash,
     467                 :             :                      .hash_info.keysize = sizeof(LOCKTAG),
     468                 :             :                      .hash_info.entrysize = sizeof(LOCK),
     469                 :             :                      .hash_info.num_partitions = NUM_LOCK_PARTITIONS,
     470                 :             :                      .hash_flags = HASH_ELEM | HASH_BLOBS | HASH_PARTITION,
     471                 :             :         );
     472                 :             : 
     473                 :             :     /* Assume an average of 2 holders per lock */
     474                 :        1271 :     max_table_size *= 2;
     475                 :             : 
     476                 :        1271 :     ShmemRequestHash(.name = "PROCLOCK hash",
     477                 :             :                      .nelems = max_table_size,
     478                 :             :                      .ptr = &LockMethodProcLockHash,
     479                 :             :                      .hash_info.keysize = sizeof(PROCLOCKTAG),
     480                 :             :                      .hash_info.entrysize = sizeof(PROCLOCK),
     481                 :             :                      .hash_info.hash = proclock_hash,
     482                 :             :                      .hash_info.num_partitions = NUM_LOCK_PARTITIONS,
     483                 :             :                      .hash_flags = HASH_ELEM | HASH_FUNCTION | HASH_PARTITION,
     484                 :             :         );
     485                 :             : 
     486                 :        1271 :     ShmemRequestStruct(.name = "Fast Path Strong Relation Lock Data",
     487                 :             :                        .size = sizeof(FastPathStrongRelationLockData),
     488                 :             :                        .ptr = (void **) (void *) &FastPathStrongRelationLocks,
     489                 :             :         );
     490                 :        1271 : }
     491                 :             : 
     492                 :             : static void
     493                 :        1268 : LockManagerShmemInit(void *arg)
     494                 :             : {
     495                 :        1268 :     SpinLockInit(&FastPathStrongRelationLocks->mutex);
     496                 :        1268 : }
     497                 :             : 
     498                 :             : /*
     499                 :             :  * Initialize the lock manager's backend-private data structures.
     500                 :             :  */
     501                 :             : void
     502                 :       25262 : InitLockManagerAccess(void)
     503                 :             : {
     504                 :             :     /*
     505                 :             :      * Allocate non-shared hash table for LOCALLOCK structs.  This stores lock
     506                 :             :      * counts and resource owner information.
     507                 :             :      */
     508                 :             :     HASHCTL     info;
     509                 :             : 
     510                 :       25262 :     info.keysize = sizeof(LOCALLOCKTAG);
     511                 :       25262 :     info.entrysize = sizeof(LOCALLOCK);
     512                 :             : 
     513                 :       25262 :     LockMethodLocalHash = hash_create("LOCALLOCK hash",
     514                 :             :                                       16,
     515                 :             :                                       &info,
     516                 :             :                                       HASH_ELEM | HASH_BLOBS);
     517                 :       25262 : }
     518                 :             : 
     519                 :             : 
     520                 :             : /*
     521                 :             :  * Fetch the lock method table associated with a given lock
     522                 :             :  */
     523                 :             : LockMethod
     524                 :         108 : GetLocksMethodTable(const LOCK *lock)
     525                 :             : {
     526                 :         108 :     LOCKMETHODID lockmethodid = LOCK_LOCKMETHOD(*lock);
     527                 :             : 
     528                 :             :     Assert(0 < lockmethodid && lockmethodid < lengthof(LockMethods));
     529                 :         108 :     return LockMethods[lockmethodid];
     530                 :             : }
     531                 :             : 
     532                 :             : /*
     533                 :             :  * Fetch the lock method table associated with a given locktag
     534                 :             :  */
     535                 :             : LockMethod
     536                 :        1287 : GetLockTagsMethodTable(const LOCKTAG *locktag)
     537                 :             : {
     538                 :        1287 :     LOCKMETHODID lockmethodid = (LOCKMETHODID) locktag->locktag_lockmethodid;
     539                 :             : 
     540                 :             :     Assert(0 < lockmethodid && lockmethodid < lengthof(LockMethods));
     541                 :        1287 :     return LockMethods[lockmethodid];
     542                 :             : }
     543                 :             : 
     544                 :             : 
     545                 :             : /*
     546                 :             :  * Compute the hash code associated with a LOCKTAG.
     547                 :             :  *
     548                 :             :  * To avoid unnecessary recomputations of the hash code, we try to do this
     549                 :             :  * just once per function, and then pass it around as needed.  Aside from
     550                 :             :  * passing the hashcode to hash_search_with_hash_value(), we can extract
     551                 :             :  * the lock partition number from the hashcode.
     552                 :             :  */
     553                 :             : uint32
     554                 :    25704084 : LockTagHashCode(const LOCKTAG *locktag)
     555                 :             : {
     556                 :    25704084 :     return get_hash_value(LockMethodLockHash, locktag);
     557                 :             : }
     558                 :             : 
     559                 :             : /*
     560                 :             :  * Compute the hash code associated with a PROCLOCKTAG.
     561                 :             :  *
     562                 :             :  * Because we want to use just one set of partition locks for both the
     563                 :             :  * LOCK and PROCLOCK hash tables, we have to make sure that PROCLOCKs
     564                 :             :  * fall into the same partition number as their associated LOCKs.
     565                 :             :  * dynahash.c expects the partition number to be the low-order bits of
     566                 :             :  * the hash code, and therefore a PROCLOCKTAG's hash code must have the
     567                 :             :  * same low-order bits as the associated LOCKTAG's hash code.  We achieve
     568                 :             :  * this with this specialized hash function.
     569                 :             :  */
     570                 :             : static uint32
     571                 :         823 : proclock_hash(const void *key, Size keysize)
     572                 :             : {
     573                 :         823 :     const PROCLOCKTAG *proclocktag = (const PROCLOCKTAG *) key;
     574                 :             :     uint32      lockhash;
     575                 :             :     Datum       procptr;
     576                 :             : 
     577                 :             :     Assert(keysize == sizeof(PROCLOCKTAG));
     578                 :             : 
     579                 :             :     /* Look into the associated LOCK object, and compute its hash code */
     580                 :         823 :     lockhash = LockTagHashCode(&proclocktag->myLock->tag);
     581                 :             : 
     582                 :             :     /*
     583                 :             :      * To make the hash code also depend on the PGPROC, we xor the proc
     584                 :             :      * struct's address into the hash code, left-shifted so that the
     585                 :             :      * partition-number bits don't change.  Since this is only a hash, we
     586                 :             :      * don't care if we lose high-order bits of the address; use an
     587                 :             :      * intermediate variable to suppress cast-pointer-to-int warnings.
     588                 :             :      */
     589                 :         823 :     procptr = PointerGetDatum(proclocktag->myProc);
     590                 :         823 :     lockhash ^= DatumGetUInt32(procptr) << LOG2_NUM_LOCK_PARTITIONS;
     591                 :             : 
     592                 :         823 :     return lockhash;
     593                 :             : }
     594                 :             : 
     595                 :             : /*
     596                 :             :  * Compute the hash code associated with a PROCLOCKTAG, given the hashcode
     597                 :             :  * for its underlying LOCK.
     598                 :             :  *
     599                 :             :  * We use this just to avoid redundant calls of LockTagHashCode().
     600                 :             :  */
     601                 :             : static inline uint32
     602                 :     5778418 : ProcLockHashCode(const PROCLOCKTAG *proclocktag, uint32 hashcode)
     603                 :             : {
     604                 :     5778418 :     uint32      lockhash = hashcode;
     605                 :             :     Datum       procptr;
     606                 :             : 
     607                 :             :     /*
     608                 :             :      * This must match proclock_hash()!
     609                 :             :      */
     610                 :     5778418 :     procptr = PointerGetDatum(proclocktag->myProc);
     611                 :     5778418 :     lockhash ^= DatumGetUInt32(procptr) << LOG2_NUM_LOCK_PARTITIONS;
     612                 :             : 
     613                 :     5778418 :     return lockhash;
     614                 :             : }
     615                 :             : 
     616                 :             : /*
     617                 :             :  * Given two lock modes, return whether they would conflict.
     618                 :             :  */
     619                 :             : bool
     620                 :       39025 : DoLockModesConflict(LOCKMODE mode1, LOCKMODE mode2)
     621                 :             : {
     622                 :       39025 :     LockMethod  lockMethodTable = LockMethods[DEFAULT_LOCKMETHOD];
     623                 :             : 
     624         [ +  + ]:       39025 :     if (lockMethodTable->conflictTab[mode1] & LOCKBIT_ON(mode2))
     625                 :         146 :         return true;
     626                 :             : 
     627                 :       38879 :     return false;
     628                 :             : }
     629                 :             : 
     630                 :             : /*
     631                 :             :  * LockHeldByMe -- test whether lock 'locktag' is held by the current
     632                 :             :  *      transaction
     633                 :             :  *
     634                 :             :  * Returns true if current transaction holds a lock on 'tag' of mode
     635                 :             :  * 'lockmode'.  If 'orstronger' is true, a stronger lockmode is also OK.
     636                 :             :  * ("Stronger" is defined as "numerically higher", which is a bit
     637                 :             :  * semantically dubious but is OK for the purposes we use this for.)
     638                 :             :  */
     639                 :             : bool
     640                 :     2048340 : LockHeldByMe(const LOCKTAG *locktag,
     641                 :             :              LOCKMODE lockmode, bool orstronger)
     642                 :             : {
     643                 :             :     LOCALLOCKTAG localtag;
     644                 :             :     LOCALLOCK  *locallock;
     645                 :             : 
     646                 :             :     /*
     647                 :             :      * See if there is a LOCALLOCK entry for this lock and lockmode
     648                 :             :      */
     649   [ +  -  -  +  :     2048340 :     MemSet(&localtag, 0, sizeof(localtag)); /* must clear padding */
          -  -  -  -  -  
                      - ]
     650                 :     2048340 :     localtag.lock = *locktag;
     651                 :     2048340 :     localtag.mode = lockmode;
     652                 :             : 
     653                 :     2048340 :     locallock = (LOCALLOCK *) hash_search(LockMethodLocalHash,
     654                 :             :                                           &localtag,
     655                 :             :                                           HASH_FIND, NULL);
     656                 :             : 
     657   [ +  +  +  - ]:     2048340 :     if (locallock && locallock->nLocks > 0)
     658                 :      304017 :         return true;
     659                 :             : 
     660         [ +  + ]:     1744323 :     if (orstronger)
     661                 :             :     {
     662                 :             :         LOCKMODE    slockmode;
     663                 :             : 
     664                 :      260216 :         for (slockmode = lockmode + 1;
     665         [ +  + ]:     1744323 :              slockmode <= MaxLockMode;
     666                 :     1484107 :              slockmode++)
     667                 :             :         {
     668         [ +  + ]:     1642960 :             if (LockHeldByMe(locktag, slockmode, false))
     669                 :      158853 :                 return true;
     670                 :             :         }
     671                 :             :     }
     672                 :             : 
     673                 :     1585470 :     return false;
     674                 :             : }
     675                 :             : 
     676                 :             : #ifdef USE_ASSERT_CHECKING
     677                 :             : /*
     678                 :             :  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
     679                 :             :  *      evaluate assertions based on all locks held.
     680                 :             :  */
     681                 :             : HTAB *
     682                 :             : GetLockMethodLocalHash(void)
     683                 :             : {
     684                 :             :     return LockMethodLocalHash;
     685                 :             : }
     686                 :             : #endif
     687                 :             : 
     688                 :             : /*
     689                 :             :  * LockHasWaiters -- look up 'locktag' and check if releasing this
     690                 :             :  *      lock would wake up other processes waiting for it.
     691                 :             :  */
     692                 :             : bool
     693                 :           0 : LockHasWaiters(const LOCKTAG *locktag, LOCKMODE lockmode, bool sessionLock)
     694                 :             : {
     695                 :           0 :     LOCKMETHODID lockmethodid = locktag->locktag_lockmethodid;
     696                 :             :     LockMethod  lockMethodTable;
     697                 :             :     LOCALLOCKTAG localtag;
     698                 :             :     LOCALLOCK  *locallock;
     699                 :             :     LOCK       *lock;
     700                 :             :     PROCLOCK   *proclock;
     701                 :             :     LWLock     *partitionLock;
     702                 :           0 :     bool        hasWaiters = false;
     703                 :             : 
     704   [ #  #  #  # ]:           0 :     if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
     705         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock method: %d", lockmethodid);
     706                 :           0 :     lockMethodTable = LockMethods[lockmethodid];
     707   [ #  #  #  # ]:           0 :     if (lockmode <= 0 || lockmode > lockMethodTable->numLockModes)
     708         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock mode: %d", lockmode);
     709                 :             : 
     710                 :             : #ifdef LOCK_DEBUG
     711                 :             :     if (LOCK_DEBUG_ENABLED(locktag))
     712                 :             :         elog(LOG, "LockHasWaiters: lock [%u,%u] %s",
     713                 :             :              locktag->locktag_field1, locktag->locktag_field2,
     714                 :             :              lockMethodTable->lockModeNames[lockmode]);
     715                 :             : #endif
     716                 :             : 
     717                 :             :     /*
     718                 :             :      * Find the LOCALLOCK entry for this lock and lockmode
     719                 :             :      */
     720   [ #  #  #  #  :           0 :     MemSet(&localtag, 0, sizeof(localtag)); /* must clear padding */
          #  #  #  #  #  
                      # ]
     721                 :           0 :     localtag.lock = *locktag;
     722                 :           0 :     localtag.mode = lockmode;
     723                 :             : 
     724                 :           0 :     locallock = (LOCALLOCK *) hash_search(LockMethodLocalHash,
     725                 :             :                                           &localtag,
     726                 :             :                                           HASH_FIND, NULL);
     727                 :             : 
     728                 :             :     /*
     729                 :             :      * let the caller print its own error message, too. Do not ereport(ERROR).
     730                 :             :      */
     731   [ #  #  #  # ]:           0 :     if (!locallock || locallock->nLocks <= 0)
     732                 :             :     {
     733         [ #  # ]:           0 :         elog(WARNING, "you don't own a lock of type %s",
     734                 :             :              lockMethodTable->lockModeNames[lockmode]);
     735                 :           0 :         return false;
     736                 :             :     }
     737                 :             : 
     738                 :             :     /*
     739                 :             :      * Check the shared lock table.
     740                 :             :      */
     741                 :           0 :     partitionLock = LockHashPartitionLock(locallock->hashcode);
     742                 :             : 
     743                 :           0 :     LWLockAcquire(partitionLock, LW_SHARED);
     744                 :             : 
     745                 :             :     /*
     746                 :             :      * We don't need to re-find the lock or proclock, since we kept their
     747                 :             :      * addresses in the locallock table, and they couldn't have been removed
     748                 :             :      * while we were holding a lock on them.
     749                 :             :      */
     750                 :           0 :     lock = locallock->lock;
     751                 :             :     LOCK_PRINT("LockHasWaiters: found", lock, lockmode);
     752                 :           0 :     proclock = locallock->proclock;
     753                 :             :     PROCLOCK_PRINT("LockHasWaiters: found", proclock);
     754                 :             : 
     755                 :             :     /*
     756                 :             :      * Double-check that we are actually holding a lock of the type we want to
     757                 :             :      * release.
     758                 :             :      */
     759         [ #  # ]:           0 :     if (!(proclock->holdMask & LOCKBIT_ON(lockmode)))
     760                 :             :     {
     761                 :             :         PROCLOCK_PRINT("LockHasWaiters: WRONGTYPE", proclock);
     762                 :           0 :         LWLockRelease(partitionLock);
     763         [ #  # ]:           0 :         elog(WARNING, "you don't own a lock of type %s",
     764                 :             :              lockMethodTable->lockModeNames[lockmode]);
     765                 :           0 :         RemoveLocalLock(locallock);
     766                 :           0 :         return false;
     767                 :             :     }
     768                 :             : 
     769                 :             :     /*
     770                 :             :      * Do the checking.
     771                 :             :      */
     772         [ #  # ]:           0 :     if ((lockMethodTable->conflictTab[lockmode] & lock->waitMask) != 0)
     773                 :           0 :         hasWaiters = true;
     774                 :             : 
     775                 :           0 :     LWLockRelease(partitionLock);
     776                 :             : 
     777                 :           0 :     return hasWaiters;
     778                 :             : }
     779                 :             : 
     780                 :             : /*
     781                 :             :  * LockAcquire -- Check for lock conflicts, sleep if conflict found,
     782                 :             :  *      set lock if/when no conflicts.
     783                 :             :  *
     784                 :             :  * Inputs:
     785                 :             :  *  locktag: unique identifier for the lockable object
     786                 :             :  *  lockmode: lock mode to acquire
     787                 :             :  *  sessionLock: if true, acquire lock for session not current transaction
     788                 :             :  *  dontWait: if true, don't wait to acquire lock
     789                 :             :  *
     790                 :             :  * Returns one of:
     791                 :             :  *      LOCKACQUIRE_NOT_AVAIL       lock not available, and dontWait=true
     792                 :             :  *      LOCKACQUIRE_OK              lock successfully acquired
     793                 :             :  *      LOCKACQUIRE_ALREADY_HELD    incremented count for lock already held
     794                 :             :  *      LOCKACQUIRE_ALREADY_CLEAR   incremented count for lock already clear
     795                 :             :  *
     796                 :             :  * In the normal case where dontWait=false and the caller doesn't need to
     797                 :             :  * distinguish a freshly acquired lock from one already taken earlier in
     798                 :             :  * this same transaction, there is no need to examine the return value.
     799                 :             :  *
     800                 :             :  * Side Effects: The lock is acquired and recorded in lock tables.
     801                 :             :  *
     802                 :             :  * NOTE: if we wait for the lock, there is no way to abort the wait
     803                 :             :  * short of aborting the transaction.
     804                 :             :  */
     805                 :             : LockAcquireResult
     806                 :     1219214 : LockAcquire(const LOCKTAG *locktag,
     807                 :             :             LOCKMODE lockmode,
     808                 :             :             bool sessionLock,
     809                 :             :             bool dontWait)
     810                 :             : {
     811                 :     1219214 :     return LockAcquireExtended(locktag, lockmode, sessionLock, dontWait,
     812                 :             :                                true, NULL, false);
     813                 :             : }
     814                 :             : 
     815                 :             : /*
     816                 :             :  * LockAcquireExtended - allows us to specify additional options
     817                 :             :  *
     818                 :             :  * reportMemoryError specifies whether a lock request that fills the lock
     819                 :             :  * table should generate an ERROR or not.  Passing "false" allows the caller
     820                 :             :  * to attempt to recover from lock-table-full situations, perhaps by forcibly
     821                 :             :  * canceling other lock holders and then retrying.  Note, however, that the
     822                 :             :  * return code for that is LOCKACQUIRE_NOT_AVAIL, so that it's unsafe to use
     823                 :             :  * in combination with dontWait = true, as the cause of failure couldn't be
     824                 :             :  * distinguished.
     825                 :             :  *
     826                 :             :  * If locallockp isn't NULL, *locallockp receives a pointer to the LOCALLOCK
     827                 :             :  * table entry if a lock is successfully acquired, or NULL if not.
     828                 :             :  *
     829                 :             :  * logLockFailure indicates whether to log details when a lock acquisition
     830                 :             :  * fails with dontWait = true.
     831                 :             :  */
     832                 :             : LockAcquireResult
     833                 :    28049877 : LockAcquireExtended(const LOCKTAG *locktag,
     834                 :             :                     LOCKMODE lockmode,
     835                 :             :                     bool sessionLock,
     836                 :             :                     bool dontWait,
     837                 :             :                     bool reportMemoryError,
     838                 :             :                     LOCALLOCK **locallockp,
     839                 :             :                     bool logLockFailure)
     840                 :             : {
     841                 :    28049877 :     LOCKMETHODID lockmethodid = locktag->locktag_lockmethodid;
     842                 :             :     LockMethod  lockMethodTable;
     843                 :             :     LOCALLOCKTAG localtag;
     844                 :             :     LOCALLOCK  *locallock;
     845                 :             :     LOCK       *lock;
     846                 :             :     PROCLOCK   *proclock;
     847                 :             :     bool        found;
     848                 :             :     ResourceOwner owner;
     849                 :             :     uint32      hashcode;
     850                 :             :     LWLock     *partitionLock;
     851                 :             :     bool        found_conflict;
     852                 :             :     ProcWaitStatus waitResult;
     853                 :    28049877 :     bool        log_lock = false;
     854                 :             : 
     855   [ +  -  -  + ]:    28049877 :     if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
     856         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock method: %d", lockmethodid);
     857                 :    28049877 :     lockMethodTable = LockMethods[lockmethodid];
     858   [ +  -  -  + ]:    28049877 :     if (lockmode <= 0 || lockmode > lockMethodTable->numLockModes)
     859         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock mode: %d", lockmode);
     860                 :             : 
     861   [ +  +  +  + ]:    28049877 :     if (RecoveryInProgress() && !InRecovery &&
     862         [ +  + ]:      397395 :         (locktag->locktag_type == LOCKTAG_OBJECT ||
     863   [ +  -  -  + ]:      397395 :          locktag->locktag_type == LOCKTAG_RELATION) &&
     864                 :             :         lockmode > RowExclusiveLock)
     865         [ #  # ]:           0 :         ereport(ERROR,
     866                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     867                 :             :                  errmsg("cannot acquire lock mode %s on database objects while recovery is in progress",
     868                 :             :                         lockMethodTable->lockModeNames[lockmode]),
     869                 :             :                  errhint("Only RowExclusiveLock or less can be acquired on database objects during recovery.")));
     870                 :             : 
     871                 :             : #ifdef LOCK_DEBUG
     872                 :             :     if (LOCK_DEBUG_ENABLED(locktag))
     873                 :             :         elog(LOG, "LockAcquire: lock [%u,%u] %s",
     874                 :             :              locktag->locktag_field1, locktag->locktag_field2,
     875                 :             :              lockMethodTable->lockModeNames[lockmode]);
     876                 :             : #endif
     877                 :             : 
     878                 :             :     /* Identify owner for lock */
     879         [ +  + ]:    28049877 :     if (sessionLock)
     880                 :      161613 :         owner = NULL;
     881                 :             :     else
     882                 :    27888264 :         owner = CurrentResourceOwner;
     883                 :             : 
     884                 :             :     /*
     885                 :             :      * Find or create a LOCALLOCK entry for this lock and lockmode
     886                 :             :      */
     887   [ +  -  -  +  :    28049877 :     MemSet(&localtag, 0, sizeof(localtag)); /* must clear padding */
          -  -  -  -  -  
                      - ]
     888                 :    28049877 :     localtag.lock = *locktag;
     889                 :    28049877 :     localtag.mode = lockmode;
     890                 :             : 
     891                 :    28049877 :     locallock = (LOCALLOCK *) hash_search(LockMethodLocalHash,
     892                 :             :                                           &localtag,
     893                 :             :                                           HASH_ENTER, &found);
     894                 :             : 
     895                 :             :     /*
     896                 :             :      * if it's a new locallock object, initialize it
     897                 :             :      */
     898         [ +  + ]:    28049877 :     if (!found)
     899                 :             :     {
     900                 :    24850792 :         locallock->lock = NULL;
     901                 :    24850792 :         locallock->proclock = NULL;
     902                 :    24850792 :         locallock->hashcode = LockTagHashCode(&(localtag.lock));
     903                 :    24850792 :         locallock->nLocks = 0;
     904                 :    24850792 :         locallock->holdsStrongLockCount = false;
     905                 :    24850792 :         locallock->lockCleared = false;
     906                 :    24850792 :         locallock->numLockOwners = 0;
     907                 :    24850792 :         locallock->maxLockOwners = 8;
     908                 :    24850792 :         locallock->lockOwners = NULL;    /* in case next line fails */
     909                 :    24850792 :         locallock->lockOwners = (LOCALLOCKOWNER *)
     910                 :    24850792 :             MemoryContextAlloc(TopMemoryContext,
     911                 :    24850792 :                                locallock->maxLockOwners * sizeof(LOCALLOCKOWNER));
     912                 :             :     }
     913                 :             :     else
     914                 :             :     {
     915                 :             :         /* Make sure there will be room to remember the lock */
     916         [ -  + ]:     3199085 :         if (locallock->lockOwners == NULL)
     917                 :             :         {
     918                 :             :             /*
     919                 :             :              * A prior acquisition may leave the array unallocated after an
     920                 :             :              * out-of-memory failure.
     921                 :             :              */
     922                 :           0 :             locallock->maxLockOwners = 8;
     923                 :           0 :             locallock->lockOwners = (LOCALLOCKOWNER *)
     924                 :           0 :                 MemoryContextAlloc(TopMemoryContext,
     925                 :           0 :                                    locallock->maxLockOwners * sizeof(LOCALLOCKOWNER));
     926                 :             :         }
     927         [ +  + ]:     3199085 :         else if (locallock->numLockOwners >= locallock->maxLockOwners)
     928                 :             :         {
     929                 :          21 :             int         newsize = locallock->maxLockOwners * 2;
     930                 :             : 
     931                 :          21 :             locallock->lockOwners = (LOCALLOCKOWNER *)
     932                 :          21 :                 repalloc(locallock->lockOwners,
     933                 :             :                          newsize * sizeof(LOCALLOCKOWNER));
     934                 :          21 :             locallock->maxLockOwners = newsize;
     935                 :             :         }
     936                 :             :     }
     937                 :    28049877 :     hashcode = locallock->hashcode;
     938                 :             : 
     939         [ +  + ]:    28049877 :     if (locallockp)
     940                 :    26830569 :         *locallockp = locallock;
     941                 :             : 
     942                 :             :     /*
     943                 :             :      * If we already hold the lock, we can just increase the count locally.
     944                 :             :      *
     945                 :             :      * If lockCleared is already set, caller need not worry about absorbing
     946                 :             :      * sinval messages related to the lock's object.
     947                 :             :      */
     948         [ +  + ]:    28049877 :     if (locallock->nLocks > 0)
     949                 :             :     {
     950                 :     3199085 :         GrantLockLocal(locallock, owner);
     951         [ +  + ]:     3199085 :         if (locallock->lockCleared)
     952                 :     3099186 :             return LOCKACQUIRE_ALREADY_CLEAR;
     953                 :             :         else
     954                 :       99899 :             return LOCKACQUIRE_ALREADY_HELD;
     955                 :             :     }
     956                 :             : 
     957                 :             :     /*
     958                 :             :      * We don't acquire any other heavyweight lock while holding the relation
     959                 :             :      * extension lock.  We do allow to acquire the same relation extension
     960                 :             :      * lock more than once but that case won't reach here.
     961                 :             :      */
     962                 :             :     Assert(!IsRelationExtensionLockHeld);
     963                 :             : 
     964                 :             :     /*
     965                 :             :      * Prepare to emit a WAL record if acquisition of this lock needs to be
     966                 :             :      * replayed in a standby server.
     967                 :             :      *
     968                 :             :      * Here we prepare to log; after lock is acquired we'll issue log record.
     969                 :             :      * This arrangement simplifies error recovery in case the preparation step
     970                 :             :      * fails.
     971                 :             :      *
     972                 :             :      * Only AccessExclusiveLocks can conflict with lock types that read-only
     973                 :             :      * transactions can acquire in a standby server. Make sure this definition
     974                 :             :      * matches the one in GetRunningTransactionLocks().
     975                 :             :      */
     976         [ +  + ]:    24850792 :     if (lockmode >= AccessExclusiveLock &&
     977         [ +  + ]:      322214 :         locktag->locktag_type == LOCKTAG_RELATION &&
     978         [ +  + ]:      211719 :         !RecoveryInProgress() &&
     979         [ +  + ]:      183445 :         XLogStandbyInfoActive())
     980                 :             :     {
     981                 :      175783 :         LogAccessExclusiveLockPrepare();
     982                 :      175783 :         log_lock = true;
     983                 :             :     }
     984                 :             : 
     985                 :             :     /*
     986                 :             :      * Attempt to take lock via fast path, if eligible.  But if we remember
     987                 :             :      * having filled up the fast path array, we don't attempt to make any
     988                 :             :      * further use of it until we release some locks.  It's possible that some
     989                 :             :      * other backend has transferred some of those locks to the shared hash
     990                 :             :      * table, leaving space free, but it's not worth acquiring the LWLock just
     991                 :             :      * to check.  It's also possible that we're acquiring a second or third
     992                 :             :      * lock type on a relation we have already locked using the fast-path, but
     993                 :             :      * for now we don't worry about that case either.
     994                 :             :      */
     995   [ +  +  +  +  :    24850792 :     if (EligibleForRelationFastPath(locktag, lockmode))
          +  +  +  +  +  
                      + ]
     996                 :             :     {
     997         [ +  + ]:    22278798 :         if (FastPathLocalUseCounts[FAST_PATH_REL_GROUP(locktag->locktag_field2)] <
     998                 :             :             FP_LOCK_SLOTS_PER_GROUP)
     999                 :             :         {
    1000                 :    22184574 :             uint32      fasthashcode = FastPathStrongLockHashPartition(hashcode);
    1001                 :             :             bool        acquired;
    1002                 :             : 
    1003                 :             :             /*
    1004                 :             :              * LWLockAcquire acts as a memory sequencing point, so it's safe
    1005                 :             :              * to assume that any strong locker whose increment to
    1006                 :             :              * FastPathStrongRelationLocks->counts becomes visible after we
    1007                 :             :              * test it has yet to begin to transfer fast-path locks.
    1008                 :             :              */
    1009                 :    22184574 :             LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
    1010         [ +  + ]:    22184574 :             if (FastPathStrongRelationLocks->count[fasthashcode] != 0)
    1011                 :      356025 :                 acquired = false;
    1012                 :             :             else
    1013                 :    21828549 :                 acquired = FastPathGrantRelationLock(locktag->locktag_field2,
    1014                 :             :                                                      lockmode);
    1015                 :    22184574 :             LWLockRelease(&MyProc->fpInfoLock);
    1016         [ +  + ]:    22184574 :             if (acquired)
    1017                 :             :             {
    1018                 :             :                 /*
    1019                 :             :                  * The locallock might contain stale pointers to some old
    1020                 :             :                  * shared objects; we MUST reset these to null before
    1021                 :             :                  * considering the lock to be acquired via fast-path.
    1022                 :             :                  */
    1023                 :    21828549 :                 locallock->lock = NULL;
    1024                 :    21828549 :                 locallock->proclock = NULL;
    1025                 :    21828549 :                 GrantLockLocal(locallock, owner);
    1026                 :    21828549 :                 return LOCKACQUIRE_OK;
    1027                 :             :             }
    1028                 :             :         }
    1029                 :             :         else
    1030                 :             :         {
    1031                 :             :             /*
    1032                 :             :              * Increment the lock statistics counter if lock could not be
    1033                 :             :              * acquired via the fast-path.
    1034                 :             :              */
    1035                 :       94224 :             pgstat_count_lock_fastpath_exceeded(locallock->tag.lock.locktag_type);
    1036                 :             :         }
    1037                 :             :     }
    1038                 :             : 
    1039                 :             :     /*
    1040                 :             :      * If this lock could potentially have been taken via the fast-path by
    1041                 :             :      * some other backend, we must (temporarily) disable further use of the
    1042                 :             :      * fast-path for this lock tag, and migrate any locks already taken via
    1043                 :             :      * this method to the main lock table.
    1044                 :             :      */
    1045   [ +  +  +  +  :     3022243 :     if (ConflictsWithRelationFastPath(locktag, lockmode))
             +  +  +  + ]
    1046                 :             :     {
    1047                 :      251906 :         uint32      fasthashcode = FastPathStrongLockHashPartition(hashcode);
    1048                 :             : 
    1049                 :      251906 :         BeginStrongLockAcquire(locallock, fasthashcode);
    1050         [ -  + ]:      251906 :         if (!FastPathTransferRelationLocks(lockMethodTable, locktag,
    1051                 :             :                                            hashcode))
    1052                 :             :         {
    1053                 :           0 :             AbortStrongLockAcquire();
    1054         [ #  # ]:           0 :             if (locallock->nLocks == 0)
    1055                 :           0 :                 RemoveLocalLock(locallock);
    1056         [ #  # ]:           0 :             if (locallockp)
    1057                 :           0 :                 *locallockp = NULL;
    1058         [ #  # ]:           0 :             if (reportMemoryError)
    1059         [ #  # ]:           0 :                 ereport(ERROR,
    1060                 :             :                         (errcode(ERRCODE_OUT_OF_MEMORY),
    1061                 :             :                          errmsg("out of shared memory"),
    1062                 :             :                          errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
    1063                 :             :             else
    1064                 :           0 :                 return LOCKACQUIRE_NOT_AVAIL;
    1065                 :             :         }
    1066                 :             :     }
    1067                 :             : 
    1068                 :             :     /*
    1069                 :             :      * We didn't find the lock in our LOCALLOCK table, and we didn't manage to
    1070                 :             :      * take it via the fast-path, either, so we've got to mess with the shared
    1071                 :             :      * lock table.
    1072                 :             :      */
    1073                 :     3022243 :     partitionLock = LockHashPartitionLock(hashcode);
    1074                 :             : 
    1075                 :     3022243 :     LWLockAcquire(partitionLock, LW_EXCLUSIVE);
    1076                 :             : 
    1077                 :             :     /*
    1078                 :             :      * Find or create lock and proclock entries with this tag
    1079                 :             :      *
    1080                 :             :      * Note: if the locallock object already existed, it might have a pointer
    1081                 :             :      * to the lock already ... but we should not assume that that pointer is
    1082                 :             :      * valid, since a lock object with zero hold and request counts can go
    1083                 :             :      * away anytime.  So we have to use SetupLockInTable() to recompute the
    1084                 :             :      * lock and proclock pointers, even if they're already set.
    1085                 :             :      */
    1086                 :     3022243 :     proclock = SetupLockInTable(lockMethodTable, MyProc, locktag,
    1087                 :             :                                 hashcode, lockmode);
    1088         [ -  + ]:     3022243 :     if (!proclock)
    1089                 :             :     {
    1090                 :           0 :         AbortStrongLockAcquire();
    1091                 :           0 :         LWLockRelease(partitionLock);
    1092         [ #  # ]:           0 :         if (locallock->nLocks == 0)
    1093                 :           0 :             RemoveLocalLock(locallock);
    1094         [ #  # ]:           0 :         if (locallockp)
    1095                 :           0 :             *locallockp = NULL;
    1096         [ #  # ]:           0 :         if (reportMemoryError)
    1097         [ #  # ]:           0 :             ereport(ERROR,
    1098                 :             :                     (errcode(ERRCODE_OUT_OF_MEMORY),
    1099                 :             :                      errmsg("out of shared memory"),
    1100                 :             :                      errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
    1101                 :             :         else
    1102                 :           0 :             return LOCKACQUIRE_NOT_AVAIL;
    1103                 :             :     }
    1104                 :     3022243 :     locallock->proclock = proclock;
    1105                 :     3022243 :     lock = proclock->tag.myLock;
    1106                 :     3022243 :     locallock->lock = lock;
    1107                 :             : 
    1108                 :             :     /*
    1109                 :             :      * If lock requested conflicts with locks requested by waiters, must join
    1110                 :             :      * wait queue.  Otherwise, check for conflict with already-held locks.
    1111                 :             :      * (That's last because most complex check.)
    1112                 :             :      */
    1113         [ +  + ]:     3022243 :     if (lockMethodTable->conflictTab[lockmode] & lock->waitMask)
    1114                 :         196 :         found_conflict = true;
    1115                 :             :     else
    1116                 :     3022047 :         found_conflict = LockCheckConflicts(lockMethodTable, lockmode,
    1117                 :             :                                             lock, proclock);
    1118                 :             : 
    1119         [ +  + ]:     3022243 :     if (!found_conflict)
    1120                 :             :     {
    1121                 :             :         /* No conflict with held or previously requested locks */
    1122                 :     3020025 :         GrantLock(lock, proclock, lockmode);
    1123                 :     3020025 :         waitResult = PROC_WAIT_STATUS_OK;
    1124                 :             :     }
    1125                 :             :     else
    1126                 :             :     {
    1127                 :             :         /*
    1128                 :             :          * Join the lock's wait queue.  We call this even in the dontWait
    1129                 :             :          * case, because JoinWaitQueue() may discover that we can acquire the
    1130                 :             :          * lock immediately after all.
    1131                 :             :          */
    1132                 :        2218 :         waitResult = JoinWaitQueue(locallock, lockMethodTable, dontWait);
    1133                 :             :     }
    1134                 :             : 
    1135         [ +  + ]:     3022243 :     if (waitResult == PROC_WAIT_STATUS_ERROR)
    1136                 :             :     {
    1137                 :             :         /*
    1138                 :             :          * We're not getting the lock because a deadlock was detected already
    1139                 :             :          * while trying to join the wait queue, or because we would have to
    1140                 :             :          * wait but the caller requested no blocking.
    1141                 :             :          *
    1142                 :             :          * Undo the changes to shared entries before releasing the partition
    1143                 :             :          * lock.
    1144                 :             :          */
    1145                 :         732 :         AbortStrongLockAcquire();
    1146                 :             : 
    1147         [ +  + ]:         732 :         if (proclock->holdMask == 0)
    1148                 :             :         {
    1149                 :             :             uint32      proclock_hashcode;
    1150                 :             : 
    1151                 :         529 :             proclock_hashcode = ProcLockHashCode(&proclock->tag,
    1152                 :             :                                                  hashcode);
    1153                 :         529 :             dlist_delete(&proclock->lockLink);
    1154                 :         529 :             dlist_delete(&proclock->procLink);
    1155         [ -  + ]:         529 :             if (!hash_search_with_hash_value(LockMethodProcLockHash,
    1156                 :         529 :                                              &(proclock->tag),
    1157                 :             :                                              proclock_hashcode,
    1158                 :             :                                              HASH_REMOVE,
    1159                 :             :                                              NULL))
    1160         [ #  # ]:           0 :                 elog(PANIC, "proclock table corrupted");
    1161                 :             :         }
    1162                 :             :         else
    1163                 :             :             PROCLOCK_PRINT("LockAcquire: did not join wait queue", proclock);
    1164                 :         732 :         lock->nRequested--;
    1165                 :         732 :         lock->requested[lockmode]--;
    1166                 :             :         LOCK_PRINT("LockAcquire: did not join wait queue",
    1167                 :             :                    lock, lockmode);
    1168                 :             :         Assert((lock->nRequested > 0) &&
    1169                 :             :                (lock->requested[lockmode] >= 0));
    1170                 :             :         Assert(lock->nGranted <= lock->nRequested);
    1171                 :         732 :         LWLockRelease(partitionLock);
    1172         [ +  - ]:         732 :         if (locallock->nLocks == 0)
    1173                 :         732 :             RemoveLocalLock(locallock);
    1174                 :             : 
    1175         [ +  + ]:         732 :         if (dontWait)
    1176                 :             :         {
    1177                 :             :             /*
    1178                 :             :              * Log lock holders and waiters as a detail log message if
    1179                 :             :              * logLockFailure = true and lock acquisition fails with dontWait
    1180                 :             :              * = true
    1181                 :             :              */
    1182         [ -  + ]:         731 :             if (logLockFailure)
    1183                 :             :             {
    1184                 :             :                 StringInfoData buf,
    1185                 :             :                             lock_waiters_sbuf,
    1186                 :             :                             lock_holders_sbuf;
    1187                 :             :                 const char *modename;
    1188                 :           0 :                 int         lockHoldersNum = 0;
    1189                 :             : 
    1190                 :           0 :                 initStringInfo(&buf);
    1191                 :           0 :                 initStringInfo(&lock_waiters_sbuf);
    1192                 :           0 :                 initStringInfo(&lock_holders_sbuf);
    1193                 :             : 
    1194                 :           0 :                 DescribeLockTag(&buf, &locallock->tag.lock);
    1195                 :           0 :                 modename = GetLockmodeName(locallock->tag.lock.locktag_lockmethodid,
    1196                 :             :                                            lockmode);
    1197                 :             : 
    1198                 :             :                 /* Gather a list of all lock holders and waiters */
    1199                 :           0 :                 LWLockAcquire(partitionLock, LW_SHARED);
    1200                 :           0 :                 GetLockHoldersAndWaiters(locallock, &lock_holders_sbuf,
    1201                 :             :                                          &lock_waiters_sbuf, &lockHoldersNum);
    1202                 :           0 :                 LWLockRelease(partitionLock);
    1203                 :             : 
    1204         [ #  # ]:           0 :                 ereport(LOG,
    1205                 :             :                         (errmsg("process %d could not obtain %s on %s",
    1206                 :             :                                 MyProcPid, modename, buf.data),
    1207                 :             :                          errdetail_log_plural(
    1208                 :             :                                               "Process holding the lock: %s, Wait queue: %s.",
    1209                 :             :                                               "Processes holding the lock: %s, Wait queue: %s.",
    1210                 :             :                                               lockHoldersNum,
    1211                 :             :                                               lock_holders_sbuf.data,
    1212                 :             :                                               lock_waiters_sbuf.data)));
    1213                 :             : 
    1214                 :           0 :                 pfree(buf.data);
    1215                 :           0 :                 pfree(lock_holders_sbuf.data);
    1216                 :           0 :                 pfree(lock_waiters_sbuf.data);
    1217                 :             :             }
    1218         [ +  + ]:         731 :             if (locallockp)
    1219                 :         222 :                 *locallockp = NULL;
    1220                 :         731 :             return LOCKACQUIRE_NOT_AVAIL;
    1221                 :             :         }
    1222                 :             :         else
    1223                 :             :         {
    1224                 :           1 :             DeadLockReport();
    1225                 :             :             /* DeadLockReport() will not return */
    1226                 :             :         }
    1227                 :             :     }
    1228                 :             : 
    1229                 :             :     /*
    1230                 :             :      * We are now in the lock queue, or the lock was already granted.  If
    1231                 :             :      * queued, go to sleep.
    1232                 :             :      */
    1233         [ +  + ]:     3021511 :     if (waitResult == PROC_WAIT_STATUS_WAITING)
    1234                 :             :     {
    1235                 :             :         Assert(!dontWait);
    1236                 :             :         PROCLOCK_PRINT("LockAcquire: sleeping on lock", proclock);
    1237                 :             :         LOCK_PRINT("LockAcquire: sleeping on lock", lock, lockmode);
    1238                 :        1481 :         LWLockRelease(partitionLock);
    1239                 :             : 
    1240                 :        1481 :         waitResult = WaitOnLock(locallock, owner);
    1241                 :             : 
    1242                 :             :         /*
    1243                 :             :          * NOTE: do not do any material change of state between here and
    1244                 :             :          * return.  All required changes in locktable state must have been
    1245                 :             :          * done when the lock was granted to us --- see notes in WaitOnLock.
    1246                 :             :          */
    1247                 :             : 
    1248         [ +  + ]:        1436 :         if (waitResult == PROC_WAIT_STATUS_ERROR)
    1249                 :             :         {
    1250                 :             :             /*
    1251                 :             :              * We failed as a result of a deadlock, see CheckDeadLock(). Quit
    1252                 :             :              * now.
    1253                 :             :              */
    1254                 :             :             Assert(!dontWait);
    1255                 :           5 :             DeadLockReport();
    1256                 :             :             /* DeadLockReport() will not return */
    1257                 :             :         }
    1258                 :             :     }
    1259                 :             :     else
    1260                 :     3020030 :         LWLockRelease(partitionLock);
    1261                 :             :     Assert(waitResult == PROC_WAIT_STATUS_OK);
    1262                 :             : 
    1263                 :             :     /* The lock was granted to us.  Update the local lock entry accordingly */
    1264                 :             :     Assert((proclock->holdMask & LOCKBIT_ON(lockmode)) != 0);
    1265                 :     3021461 :     GrantLockLocal(locallock, owner);
    1266                 :             : 
    1267                 :             :     /*
    1268                 :             :      * Lock state is fully up-to-date now; if we error out after this, no
    1269                 :             :      * special error cleanup is required.
    1270                 :             :      */
    1271                 :     3021461 :     FinishStrongLockAcquire();
    1272                 :             : 
    1273                 :             :     /*
    1274                 :             :      * Emit a WAL record if acquisition of this lock needs to be replayed in a
    1275                 :             :      * standby server.
    1276                 :             :      */
    1277         [ +  + ]:     3021461 :     if (log_lock)
    1278                 :             :     {
    1279                 :             :         /*
    1280                 :             :          * Decode the locktag back to the original values, to avoid sending
    1281                 :             :          * lots of empty bytes with every message.  See lock.h to check how a
    1282                 :             :          * locktag is defined for LOCKTAG_RELATION
    1283                 :             :          */
    1284                 :      175570 :         LogAccessExclusiveLock(locktag->locktag_field1,
    1285                 :      175570 :                                locktag->locktag_field2);
    1286                 :             :     }
    1287                 :             : 
    1288                 :     3021461 :     return LOCKACQUIRE_OK;
    1289                 :             : }
    1290                 :             : 
    1291                 :             : /*
    1292                 :             :  * Find or create LOCK and PROCLOCK objects as needed for a new lock
    1293                 :             :  * request.
    1294                 :             :  *
    1295                 :             :  * Returns the PROCLOCK object, or NULL if we failed to create the objects
    1296                 :             :  * for lack of shared memory.
    1297                 :             :  *
    1298                 :             :  * The appropriate partition lock must be held at entry, and will be
    1299                 :             :  * held at exit.
    1300                 :             :  */
    1301                 :             : static PROCLOCK *
    1302                 :     3024489 : SetupLockInTable(LockMethod lockMethodTable, PGPROC *proc,
    1303                 :             :                  const LOCKTAG *locktag, uint32 hashcode, LOCKMODE lockmode)
    1304                 :             : {
    1305                 :             :     LOCK       *lock;
    1306                 :             :     PROCLOCK   *proclock;
    1307                 :             :     PROCLOCKTAG proclocktag;
    1308                 :             :     uint32      proclock_hashcode;
    1309                 :             :     bool        found;
    1310                 :             : 
    1311                 :             :     /*
    1312                 :             :      * Find or create a lock with this tag.
    1313                 :             :      */
    1314                 :     3024489 :     lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
    1315                 :             :                                                 locktag,
    1316                 :             :                                                 hashcode,
    1317                 :             :                                                 HASH_ENTER_NULL,
    1318                 :             :                                                 &found);
    1319         [ -  + ]:     3024489 :     if (!lock)
    1320                 :           0 :         return NULL;
    1321                 :             : 
    1322                 :             :     /*
    1323                 :             :      * if it's a new lock object, initialize it
    1324                 :             :      */
    1325         [ +  + ]:     3024489 :     if (!found)
    1326                 :             :     {
    1327                 :     2712415 :         lock->grantMask = 0;
    1328                 :     2712415 :         lock->waitMask = 0;
    1329                 :     2712415 :         dlist_init(&lock->procLocks);
    1330                 :     2712415 :         dclist_init(&lock->waitProcs);
    1331                 :     2712415 :         lock->nRequested = 0;
    1332                 :     2712415 :         lock->nGranted = 0;
    1333   [ +  -  +  -  :    16274490 :         MemSet(lock->requested, 0, sizeof(int) * MAX_LOCKMODES);
          +  -  +  -  +  
                      + ]
    1334   [ -  +  -  -  :     2712415 :         MemSet(lock->granted, 0, sizeof(int) * MAX_LOCKMODES);
          -  -  -  -  -  
                      - ]
    1335                 :             :         LOCK_PRINT("LockAcquire: new", lock, lockmode);
    1336                 :             :     }
    1337                 :             :     else
    1338                 :             :     {
    1339                 :             :         LOCK_PRINT("LockAcquire: found", lock, lockmode);
    1340                 :             :         Assert((lock->nRequested >= 0) && (lock->requested[lockmode] >= 0));
    1341                 :             :         Assert((lock->nGranted >= 0) && (lock->granted[lockmode] >= 0));
    1342                 :             :         Assert(lock->nGranted <= lock->nRequested);
    1343                 :             :     }
    1344                 :             : 
    1345                 :             :     /*
    1346                 :             :      * Create the hash key for the proclock table.
    1347                 :             :      */
    1348                 :     3024489 :     proclocktag.myLock = lock;
    1349                 :     3024489 :     proclocktag.myProc = proc;
    1350                 :             : 
    1351                 :     3024489 :     proclock_hashcode = ProcLockHashCode(&proclocktag, hashcode);
    1352                 :             : 
    1353                 :             :     /*
    1354                 :             :      * Find or create a proclock entry with this tag
    1355                 :             :      */
    1356                 :     3024489 :     proclock = (PROCLOCK *) hash_search_with_hash_value(LockMethodProcLockHash,
    1357                 :             :                                                         &proclocktag,
    1358                 :             :                                                         proclock_hashcode,
    1359                 :             :                                                         HASH_ENTER_NULL,
    1360                 :             :                                                         &found);
    1361         [ -  + ]:     3024489 :     if (!proclock)
    1362                 :             :     {
    1363                 :             :         /* Oops, not enough shmem for the proclock */
    1364         [ #  # ]:           0 :         if (lock->nRequested == 0)
    1365                 :             :         {
    1366                 :             :             /*
    1367                 :             :              * There are no other requestors of this lock, so garbage-collect
    1368                 :             :              * the lock object.  We *must* do this to avoid a permanent leak
    1369                 :             :              * of shared memory, because there won't be anything to cause
    1370                 :             :              * anyone to release the lock object later.
    1371                 :             :              */
    1372                 :             :             Assert(dlist_is_empty(&(lock->procLocks)));
    1373         [ #  # ]:           0 :             if (!hash_search_with_hash_value(LockMethodLockHash,
    1374                 :           0 :                                              &(lock->tag),
    1375                 :             :                                              hashcode,
    1376                 :             :                                              HASH_REMOVE,
    1377                 :             :                                              NULL))
    1378         [ #  # ]:           0 :                 elog(PANIC, "lock table corrupted");
    1379                 :             :         }
    1380                 :           0 :         return NULL;
    1381                 :             :     }
    1382                 :             : 
    1383                 :             :     /*
    1384                 :             :      * If new, initialize the new entry
    1385                 :             :      */
    1386         [ +  + ]:     3024489 :     if (!found)
    1387                 :             :     {
    1388                 :     2750999 :         uint32      partition = LockHashPartition(hashcode);
    1389                 :             : 
    1390                 :             :         /*
    1391                 :             :          * It might seem unsafe to access proclock->groupLeader without a
    1392                 :             :          * lock, but it's not really.  Either we are initializing a proclock
    1393                 :             :          * on our own behalf, in which case our group leader isn't changing
    1394                 :             :          * because the group leader for a process can only ever be changed by
    1395                 :             :          * the process itself; or else we are transferring a fast-path lock to
    1396                 :             :          * the main lock table, in which case that process can't change its
    1397                 :             :          * lock group leader without first releasing all of its locks (and in
    1398                 :             :          * particular the one we are currently transferring).
    1399                 :             :          */
    1400                 :     5501998 :         proclock->groupLeader = proc->lockGroupLeader != NULL ?
    1401         [ +  + ]:     2750999 :             proc->lockGroupLeader : proc;
    1402                 :     2750999 :         proclock->holdMask = 0;
    1403                 :     2750999 :         proclock->releaseMask = 0;
    1404                 :             :         /* Add proclock to appropriate lists */
    1405                 :     2750999 :         dlist_push_tail(&lock->procLocks, &proclock->lockLink);
    1406                 :     2750999 :         dlist_push_tail(&proc->myProcLocks[partition], &proclock->procLink);
    1407                 :             :         PROCLOCK_PRINT("LockAcquire: new", proclock);
    1408                 :             :     }
    1409                 :             :     else
    1410                 :             :     {
    1411                 :             :         PROCLOCK_PRINT("LockAcquire: found", proclock);
    1412                 :             :         Assert((proclock->holdMask & ~lock->grantMask) == 0);
    1413                 :             : 
    1414                 :             : #ifdef CHECK_DEADLOCK_RISK
    1415                 :             : 
    1416                 :             :         /*
    1417                 :             :          * Issue warning if we already hold a lower-level lock on this object
    1418                 :             :          * and do not hold a lock of the requested level or higher. This
    1419                 :             :          * indicates a deadlock-prone coding practice (eg, we'd have a
    1420                 :             :          * deadlock if another backend were following the same code path at
    1421                 :             :          * about the same time).
    1422                 :             :          *
    1423                 :             :          * This is not enabled by default, because it may generate log entries
    1424                 :             :          * about user-level coding practices that are in fact safe in context.
    1425                 :             :          * It can be enabled to help find system-level problems.
    1426                 :             :          *
    1427                 :             :          * XXX Doing numeric comparison on the lockmodes is a hack; it'd be
    1428                 :             :          * better to use a table.  For now, though, this works.
    1429                 :             :          */
    1430                 :             :         {
    1431                 :             :             int         i;
    1432                 :             : 
    1433                 :             :             for (i = lockMethodTable->numLockModes; i > 0; i--)
    1434                 :             :             {
    1435                 :             :                 if (proclock->holdMask & LOCKBIT_ON(i))
    1436                 :             :                 {
    1437                 :             :                     if (i >= (int) lockmode)
    1438                 :             :                         break;  /* safe: we have a lock >= req level */
    1439                 :             :                     elog(LOG, "deadlock risk: raising lock level"
    1440                 :             :                          " from %s to %s on object %u/%u/%u",
    1441                 :             :                          lockMethodTable->lockModeNames[i],
    1442                 :             :                          lockMethodTable->lockModeNames[lockmode],
    1443                 :             :                          lock->tag.locktag_field1, lock->tag.locktag_field2,
    1444                 :             :                          lock->tag.locktag_field3);
    1445                 :             :                     break;
    1446                 :             :                 }
    1447                 :             :             }
    1448                 :             :         }
    1449                 :             : #endif                          /* CHECK_DEADLOCK_RISK */
    1450                 :             :     }
    1451                 :             : 
    1452                 :             :     /*
    1453                 :             :      * lock->nRequested and lock->requested[] count the total number of
    1454                 :             :      * requests, whether granted or waiting, so increment those immediately.
    1455                 :             :      * The other counts don't increment till we get the lock.
    1456                 :             :      */
    1457                 :     3024489 :     lock->nRequested++;
    1458                 :     3024489 :     lock->requested[lockmode]++;
    1459                 :             :     Assert((lock->nRequested > 0) && (lock->requested[lockmode] > 0));
    1460                 :             : 
    1461                 :             :     /*
    1462                 :             :      * We shouldn't already hold the desired lock; else locallock table is
    1463                 :             :      * broken.
    1464                 :             :      */
    1465         [ -  + ]:     3024489 :     if (proclock->holdMask & LOCKBIT_ON(lockmode))
    1466         [ #  # ]:           0 :         elog(ERROR, "lock %s on object %u/%u/%u is already held",
    1467                 :             :              lockMethodTable->lockModeNames[lockmode],
    1468                 :             :              lock->tag.locktag_field1, lock->tag.locktag_field2,
    1469                 :             :              lock->tag.locktag_field3);
    1470                 :             : 
    1471                 :     3024489 :     return proclock;
    1472                 :             : }
    1473                 :             : 
    1474                 :             : /*
    1475                 :             :  * Check and set/reset the flag that we hold the relation extension lock.
    1476                 :             :  *
    1477                 :             :  * It is callers responsibility that this function is called after
    1478                 :             :  * acquiring/releasing the relation extension lock.
    1479                 :             :  *
    1480                 :             :  * Pass acquired as true if lock is acquired, false otherwise.
    1481                 :             :  */
    1482                 :             : static inline void
    1483                 :    50882147 : CheckAndSetLockHeld(LOCALLOCK *locallock, bool acquired)
    1484                 :             : {
    1485                 :             : #ifdef USE_ASSERT_CHECKING
    1486                 :             :     if (LOCALLOCK_LOCKTAG(*locallock) == LOCKTAG_RELATION_EXTEND)
    1487                 :             :         IsRelationExtensionLockHeld = acquired;
    1488                 :             : #endif
    1489                 :    50882147 : }
    1490                 :             : 
    1491                 :             : /*
    1492                 :             :  * Subroutine to free a locallock entry
    1493                 :             :  */
    1494                 :             : static void
    1495                 :    24850792 : RemoveLocalLock(LOCALLOCK *locallock)
    1496                 :             : {
    1497                 :             :     int         i;
    1498                 :             : 
    1499         [ +  + ]:    24960267 :     for (i = locallock->numLockOwners - 1; i >= 0; i--)
    1500                 :             :     {
    1501         [ +  + ]:      109475 :         if (locallock->lockOwners[i].owner != NULL)
    1502                 :      109415 :             ResourceOwnerForgetLock(locallock->lockOwners[i].owner, locallock);
    1503                 :             :     }
    1504                 :    24850792 :     locallock->numLockOwners = 0;
    1505         [ +  - ]:    24850792 :     if (locallock->lockOwners != NULL)
    1506                 :    24850792 :         pfree(locallock->lockOwners);
    1507                 :    24850792 :     locallock->lockOwners = NULL;
    1508                 :             : 
    1509         [ +  + ]:    24850792 :     if (locallock->holdsStrongLockCount)
    1510                 :             :     {
    1511                 :             :         uint32      fasthashcode;
    1512                 :             : 
    1513                 :      251575 :         fasthashcode = FastPathStrongLockHashPartition(locallock->hashcode);
    1514                 :             : 
    1515                 :      251575 :         SpinLockAcquire(&FastPathStrongRelationLocks->mutex);
    1516                 :             :         Assert(FastPathStrongRelationLocks->count[fasthashcode] > 0);
    1517                 :      251575 :         FastPathStrongRelationLocks->count[fasthashcode]--;
    1518                 :      251575 :         locallock->holdsStrongLockCount = false;
    1519                 :      251575 :         SpinLockRelease(&FastPathStrongRelationLocks->mutex);
    1520                 :             :     }
    1521                 :             : 
    1522         [ -  + ]:    24850792 :     if (!hash_search(LockMethodLocalHash,
    1523                 :    24850792 :                      &(locallock->tag),
    1524                 :             :                      HASH_REMOVE, NULL))
    1525         [ #  # ]:           0 :         elog(WARNING, "locallock table corrupted");
    1526                 :             : 
    1527                 :             :     /*
    1528                 :             :      * Indicate that the lock is released for certain types of locks
    1529                 :             :      */
    1530                 :    24850792 :     CheckAndSetLockHeld(locallock, false);
    1531                 :    24850792 : }
    1532                 :             : 
    1533                 :             : /*
    1534                 :             :  * LockCheckConflicts -- test whether requested lock conflicts
    1535                 :             :  *      with those already granted
    1536                 :             :  *
    1537                 :             :  * Returns true if conflict, false if no conflict.
    1538                 :             :  *
    1539                 :             :  * NOTES:
    1540                 :             :  *      Here's what makes this complicated: one process's locks don't
    1541                 :             :  * conflict with one another, no matter what purpose they are held for
    1542                 :             :  * (eg, session and transaction locks do not conflict).  Nor do the locks
    1543                 :             :  * of one process in a lock group conflict with those of another process in
    1544                 :             :  * the same group.  So, we must subtract off these locks when determining
    1545                 :             :  * whether the requested new lock conflicts with those already held.
    1546                 :             :  */
    1547                 :             : bool
    1548                 :     3023700 : LockCheckConflicts(LockMethod lockMethodTable,
    1549                 :             :                    LOCKMODE lockmode,
    1550                 :             :                    LOCK *lock,
    1551                 :             :                    PROCLOCK *proclock)
    1552                 :             : {
    1553                 :     3023700 :     int         numLockModes = lockMethodTable->numLockModes;
    1554                 :             :     LOCKMASK    myLocks;
    1555                 :     3023700 :     int         conflictMask = lockMethodTable->conflictTab[lockmode];
    1556                 :             :     int         conflictsRemaining[MAX_LOCKMODES];
    1557                 :     3023700 :     int         totalConflictsRemaining = 0;
    1558                 :             :     dlist_iter  proclock_iter;
    1559                 :             :     int         i;
    1560                 :             : 
    1561                 :             :     /*
    1562                 :             :      * first check for global conflicts: If no locks conflict with my request,
    1563                 :             :      * then I get the lock.
    1564                 :             :      *
    1565                 :             :      * Checking for conflict: lock->grantMask represents the types of
    1566                 :             :      * currently held locks.  conflictTable[lockmode] has a bit set for each
    1567                 :             :      * type of lock that conflicts with request.   Bitwise compare tells if
    1568                 :             :      * there is a conflict.
    1569                 :             :      */
    1570         [ +  + ]:     3023700 :     if (!(conflictMask & lock->grantMask))
    1571                 :             :     {
    1572                 :             :         PROCLOCK_PRINT("LockCheckConflicts: no conflict", proclock);
    1573                 :     2899634 :         return false;
    1574                 :             :     }
    1575                 :             : 
    1576                 :             :     /*
    1577                 :             :      * Rats.  Something conflicts.  But it could still be my own lock, or a
    1578                 :             :      * lock held by another member of my locking group.  First, figure out how
    1579                 :             :      * many conflicts remain after subtracting out any locks I hold myself.
    1580                 :             :      */
    1581                 :      124066 :     myLocks = proclock->holdMask;
    1582         [ +  + ]:     1116594 :     for (i = 1; i <= numLockModes; i++)
    1583                 :             :     {
    1584         [ +  + ]:      992528 :         if ((conflictMask & LOCKBIT_ON(i)) == 0)
    1585                 :             :         {
    1586                 :      522461 :             conflictsRemaining[i] = 0;
    1587                 :      522461 :             continue;
    1588                 :             :         }
    1589                 :      470067 :         conflictsRemaining[i] = lock->granted[i];
    1590         [ +  + ]:      470067 :         if (myLocks & LOCKBIT_ON(i))
    1591                 :      134114 :             --conflictsRemaining[i];
    1592                 :      470067 :         totalConflictsRemaining += conflictsRemaining[i];
    1593                 :             :     }
    1594                 :             : 
    1595                 :             :     /* If no conflicts remain, we get the lock. */
    1596         [ +  + ]:      124066 :     if (totalConflictsRemaining == 0)
    1597                 :             :     {
    1598                 :             :         PROCLOCK_PRINT("LockCheckConflicts: resolved (simple)", proclock);
    1599                 :      121039 :         return false;
    1600                 :             :     }
    1601                 :             : 
    1602                 :             :     /* If no group locking, it's definitely a conflict. */
    1603   [ +  +  +  + ]:        3027 :     if (proclock->groupLeader == MyProc && MyProc->lockGroupLeader == NULL)
    1604                 :             :     {
    1605                 :             :         Assert(proclock->tag.myProc == MyProc);
    1606                 :             :         PROCLOCK_PRINT("LockCheckConflicts: conflicting (simple)",
    1607                 :             :                        proclock);
    1608                 :        2015 :         return true;
    1609                 :             :     }
    1610                 :             : 
    1611                 :             :     /*
    1612                 :             :      * The relation extension lock conflict even between the group members.
    1613                 :             :      */
    1614         [ +  + ]:        1012 :     if (LOCK_LOCKTAG(*lock) == LOCKTAG_RELATION_EXTEND)
    1615                 :             :     {
    1616                 :             :         PROCLOCK_PRINT("LockCheckConflicts: conflicting (group)",
    1617                 :             :                        proclock);
    1618                 :          18 :         return true;
    1619                 :             :     }
    1620                 :             : 
    1621                 :             :     /*
    1622                 :             :      * Locks held in conflicting modes by members of our own lock group are
    1623                 :             :      * not real conflicts; we can subtract those out and see if we still have
    1624                 :             :      * a conflict.  This is O(N) in the number of processes holding or
    1625                 :             :      * awaiting locks on this object.  We could improve that by making the
    1626                 :             :      * shared memory state more complex (and larger) but it doesn't seem worth
    1627                 :             :      * it.
    1628                 :             :      */
    1629   [ +  -  +  + ]:        1759 :     dlist_foreach(proclock_iter, &lock->procLocks)
    1630                 :             :     {
    1631                 :        1556 :         PROCLOCK   *otherproclock =
    1632                 :        1556 :             dlist_container(PROCLOCK, lockLink, proclock_iter.cur);
    1633                 :             : 
    1634         [ +  + ]:        1556 :         if (proclock != otherproclock &&
    1635         [ +  + ]:        1353 :             proclock->groupLeader == otherproclock->groupLeader &&
    1636         [ +  + ]:         804 :             (otherproclock->holdMask & conflictMask) != 0)
    1637                 :             :         {
    1638                 :         802 :             int         intersectMask = otherproclock->holdMask & conflictMask;
    1639                 :             : 
    1640         [ +  + ]:        7218 :             for (i = 1; i <= numLockModes; i++)
    1641                 :             :             {
    1642         [ +  + ]:        6416 :                 if ((intersectMask & LOCKBIT_ON(i)) != 0)
    1643                 :             :                 {
    1644         [ -  + ]:         815 :                     if (conflictsRemaining[i] <= 0)
    1645         [ #  # ]:           0 :                         elog(PANIC, "proclocks held do not match lock");
    1646                 :         815 :                     conflictsRemaining[i]--;
    1647                 :         815 :                     totalConflictsRemaining--;
    1648                 :             :                 }
    1649                 :             :             }
    1650                 :             : 
    1651         [ +  + ]:         802 :             if (totalConflictsRemaining == 0)
    1652                 :             :             {
    1653                 :             :                 PROCLOCK_PRINT("LockCheckConflicts: resolved (group)",
    1654                 :             :                                proclock);
    1655                 :         791 :                 return false;
    1656                 :             :             }
    1657                 :             :         }
    1658                 :             :     }
    1659                 :             : 
    1660                 :             :     /* Nope, it's a real conflict. */
    1661                 :             :     PROCLOCK_PRINT("LockCheckConflicts: conflicting (group)", proclock);
    1662                 :         203 :     return true;
    1663                 :             : }
    1664                 :             : 
    1665                 :             : /*
    1666                 :             :  * GrantLock -- update the lock and proclock data structures to show
    1667                 :             :  *      the lock request has been granted.
    1668                 :             :  *
    1669                 :             :  * NOTE: if proc was blocked, it also needs to be removed from the wait list
    1670                 :             :  * and have its waitLock/waitProcLock fields cleared.  That's not done here.
    1671                 :             :  *
    1672                 :             :  * NOTE: the lock grant also has to be recorded in the associated LOCALLOCK
    1673                 :             :  * table entry; but since we may be awaking some other process, we can't do
    1674                 :             :  * that here; it's done by GrantLockLocal, instead.
    1675                 :             :  */
    1676                 :             : void
    1677                 :     3023806 : GrantLock(LOCK *lock, PROCLOCK *proclock, LOCKMODE lockmode)
    1678                 :             : {
    1679                 :     3023806 :     lock->nGranted++;
    1680                 :     3023806 :     lock->granted[lockmode]++;
    1681                 :     3023806 :     lock->grantMask |= LOCKBIT_ON(lockmode);
    1682         [ +  + ]:     3023806 :     if (lock->granted[lockmode] == lock->requested[lockmode])
    1683                 :     3023459 :         lock->waitMask &= LOCKBIT_OFF(lockmode);
    1684                 :     3023806 :     proclock->holdMask |= LOCKBIT_ON(lockmode);
    1685                 :             :     LOCK_PRINT("GrantLock", lock, lockmode);
    1686                 :             :     Assert((lock->nGranted > 0) && (lock->granted[lockmode] > 0));
    1687                 :             :     Assert(lock->nGranted <= lock->nRequested);
    1688                 :     3023806 : }
    1689                 :             : 
    1690                 :             : /*
    1691                 :             :  * UnGrantLock -- opposite of GrantLock.
    1692                 :             :  *
    1693                 :             :  * Updates the lock and proclock data structures to show that the lock
    1694                 :             :  * is no longer held nor requested by the current holder.
    1695                 :             :  *
    1696                 :             :  * Returns true if there were any waiters waiting on the lock that
    1697                 :             :  * should now be woken up with ProcLockWakeup.
    1698                 :             :  */
    1699                 :             : static bool
    1700                 :     3023720 : UnGrantLock(LOCK *lock, LOCKMODE lockmode,
    1701                 :             :             PROCLOCK *proclock, LockMethod lockMethodTable)
    1702                 :             : {
    1703                 :     3023720 :     bool        wakeupNeeded = false;
    1704                 :             : 
    1705                 :             :     Assert((lock->nRequested > 0) && (lock->requested[lockmode] > 0));
    1706                 :             :     Assert((lock->nGranted > 0) && (lock->granted[lockmode] > 0));
    1707                 :             :     Assert(lock->nGranted <= lock->nRequested);
    1708                 :             : 
    1709                 :             :     /*
    1710                 :             :      * fix the general lock stats
    1711                 :             :      */
    1712                 :     3023720 :     lock->nRequested--;
    1713                 :     3023720 :     lock->requested[lockmode]--;
    1714                 :     3023720 :     lock->nGranted--;
    1715                 :     3023720 :     lock->granted[lockmode]--;
    1716                 :             : 
    1717         [ +  + ]:     3023720 :     if (lock->granted[lockmode] == 0)
    1718                 :             :     {
    1719                 :             :         /* change the conflict mask.  No more of this lock type. */
    1720                 :     2999950 :         lock->grantMask &= LOCKBIT_OFF(lockmode);
    1721                 :             :     }
    1722                 :             : 
    1723                 :             :     LOCK_PRINT("UnGrantLock: updated", lock, lockmode);
    1724                 :             : 
    1725                 :             :     /*
    1726                 :             :      * We need only run ProcLockWakeup if the released lock conflicts with at
    1727                 :             :      * least one of the lock types requested by waiter(s).  Otherwise whatever
    1728                 :             :      * conflict made them wait must still exist.  NOTE: before MVCC, we could
    1729                 :             :      * skip wakeup if lock->granted[lockmode] was still positive. But that's
    1730                 :             :      * not true anymore, because the remaining granted locks might belong to
    1731                 :             :      * some waiter, who could now be awakened because he doesn't conflict with
    1732                 :             :      * his own locks.
    1733                 :             :      */
    1734         [ +  + ]:     3023720 :     if (lockMethodTable->conflictTab[lockmode] & lock->waitMask)
    1735                 :        1394 :         wakeupNeeded = true;
    1736                 :             : 
    1737                 :             :     /*
    1738                 :             :      * Now fix the per-proclock state.
    1739                 :             :      */
    1740                 :     3023720 :     proclock->holdMask &= LOCKBIT_OFF(lockmode);
    1741                 :             :     PROCLOCK_PRINT("UnGrantLock: updated", proclock);
    1742                 :             : 
    1743                 :     3023720 :     return wakeupNeeded;
    1744                 :             : }
    1745                 :             : 
    1746                 :             : /*
    1747                 :             :  * CleanUpLock -- clean up after releasing a lock.  We garbage-collect the
    1748                 :             :  * proclock and lock objects if possible, and call ProcLockWakeup if there
    1749                 :             :  * are remaining requests and the caller says it's OK.  (Normally, this
    1750                 :             :  * should be called after UnGrantLock, and wakeupNeeded is the result from
    1751                 :             :  * UnGrantLock.)
    1752                 :             :  *
    1753                 :             :  * The appropriate partition lock must be held at entry, and will be
    1754                 :             :  * held at exit.
    1755                 :             :  */
    1756                 :             : static void
    1757                 :     2975388 : CleanUpLock(LOCK *lock, PROCLOCK *proclock,
    1758                 :             :             LockMethod lockMethodTable, uint32 hashcode,
    1759                 :             :             bool wakeupNeeded)
    1760                 :             : {
    1761                 :             :     /*
    1762                 :             :      * If this was my last hold on this lock, delete my entry in the proclock
    1763                 :             :      * table.
    1764                 :             :      */
    1765         [ +  + ]:     2975388 :     if (proclock->holdMask == 0)
    1766                 :             :     {
    1767                 :             :         uint32      proclock_hashcode;
    1768                 :             : 
    1769                 :             :         PROCLOCK_PRINT("CleanUpLock: deleting", proclock);
    1770                 :     2750480 :         dlist_delete(&proclock->lockLink);
    1771                 :     2750480 :         dlist_delete(&proclock->procLink);
    1772                 :     2750480 :         proclock_hashcode = ProcLockHashCode(&proclock->tag, hashcode);
    1773         [ -  + ]:     2750480 :         if (!hash_search_with_hash_value(LockMethodProcLockHash,
    1774                 :     2750480 :                                          &(proclock->tag),
    1775                 :             :                                          proclock_hashcode,
    1776                 :             :                                          HASH_REMOVE,
    1777                 :             :                                          NULL))
    1778         [ #  # ]:           0 :             elog(PANIC, "proclock table corrupted");
    1779                 :             :     }
    1780                 :             : 
    1781         [ +  + ]:     2975388 :     if (lock->nRequested == 0)
    1782                 :             :     {
    1783                 :             :         /*
    1784                 :             :          * The caller just released the last lock, so garbage-collect the lock
    1785                 :             :          * object.
    1786                 :             :          */
    1787                 :             :         LOCK_PRINT("CleanUpLock: deleting", lock, 0);
    1788                 :             :         Assert(dlist_is_empty(&lock->procLocks));
    1789         [ -  + ]:     2712425 :         if (!hash_search_with_hash_value(LockMethodLockHash,
    1790                 :     2712425 :                                          &(lock->tag),
    1791                 :             :                                          hashcode,
    1792                 :             :                                          HASH_REMOVE,
    1793                 :             :                                          NULL))
    1794         [ #  # ]:           0 :             elog(PANIC, "lock table corrupted");
    1795                 :             :     }
    1796         [ +  + ]:      262963 :     else if (wakeupNeeded)
    1797                 :             :     {
    1798                 :             :         /* There are waiters on this lock, so wake them up. */
    1799                 :        1439 :         ProcLockWakeup(lockMethodTable, lock);
    1800                 :             :     }
    1801                 :     2975388 : }
    1802                 :             : 
    1803                 :             : /*
    1804                 :             :  * GrantLockLocal -- update the locallock data structures to show
    1805                 :             :  *      the lock request has been granted.
    1806                 :             :  *
    1807                 :             :  * We expect that LockAcquire made sure there is room to add a new
    1808                 :             :  * ResourceOwner entry.
    1809                 :             :  */
    1810                 :             : static void
    1811                 :    28049097 : GrantLockLocal(LOCALLOCK *locallock, ResourceOwner owner)
    1812                 :             : {
    1813                 :    28049097 :     LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
    1814                 :             :     int         i;
    1815                 :             : 
    1816                 :             :     Assert(locallock->numLockOwners < locallock->maxLockOwners);
    1817                 :             :     /* Count the total */
    1818                 :    28049097 :     locallock->nLocks++;
    1819                 :             :     /* Count the per-owner lock */
    1820         [ +  + ]:    29934867 :     for (i = 0; i < locallock->numLockOwners; i++)
    1821                 :             :     {
    1822         [ +  + ]:     3903512 :         if (lockOwners[i].owner == owner)
    1823                 :             :         {
    1824                 :     2017742 :             lockOwners[i].nLocks++;
    1825                 :     2017742 :             return;
    1826                 :             :         }
    1827                 :             :     }
    1828                 :    26031355 :     lockOwners[i].owner = owner;
    1829                 :    26031355 :     lockOwners[i].nLocks = 1;
    1830                 :    26031355 :     locallock->numLockOwners++;
    1831         [ +  + ]:    26031355 :     if (owner != NULL)
    1832                 :    25870271 :         ResourceOwnerRememberLock(owner, locallock);
    1833                 :             : 
    1834                 :             :     /* Indicate that the lock is acquired for certain types of locks. */
    1835                 :    26031355 :     CheckAndSetLockHeld(locallock, true);
    1836                 :             : }
    1837                 :             : 
    1838                 :             : /*
    1839                 :             :  * BeginStrongLockAcquire - inhibit use of fastpath for a given LOCALLOCK,
    1840                 :             :  * and arrange for error cleanup if it fails
    1841                 :             :  */
    1842                 :             : static void
    1843                 :      251906 : BeginStrongLockAcquire(LOCALLOCK *locallock, uint32 fasthashcode)
    1844                 :             : {
    1845                 :             :     Assert(StrongLockInProgress == NULL);
    1846                 :             :     Assert(locallock->holdsStrongLockCount == false);
    1847                 :             : 
    1848                 :             :     /*
    1849                 :             :      * Adding to a memory location is not atomic, so we take a spinlock to
    1850                 :             :      * ensure we don't collide with someone else trying to bump the count at
    1851                 :             :      * the same time.
    1852                 :             :      *
    1853                 :             :      * XXX: It might be worth considering using an atomic fetch-and-add
    1854                 :             :      * instruction here, on architectures where that is supported.
    1855                 :             :      */
    1856                 :             : 
    1857                 :      251906 :     SpinLockAcquire(&FastPathStrongRelationLocks->mutex);
    1858                 :      251906 :     FastPathStrongRelationLocks->count[fasthashcode]++;
    1859                 :      251906 :     locallock->holdsStrongLockCount = true;
    1860                 :      251906 :     StrongLockInProgress = locallock;
    1861                 :      251906 :     SpinLockRelease(&FastPathStrongRelationLocks->mutex);
    1862                 :      251906 : }
    1863                 :             : 
    1864                 :             : /*
    1865                 :             :  * FinishStrongLockAcquire - cancel pending cleanup for a strong lock
    1866                 :             :  * acquisition once it's no longer needed
    1867                 :             :  */
    1868                 :             : static void
    1869                 :     3021461 : FinishStrongLockAcquire(void)
    1870                 :             : {
    1871                 :     3021461 :     StrongLockInProgress = NULL;
    1872                 :     3021461 : }
    1873                 :             : 
    1874                 :             : /*
    1875                 :             :  * AbortStrongLockAcquire - undo strong lock state changes performed by
    1876                 :             :  * BeginStrongLockAcquire.
    1877                 :             :  */
    1878                 :             : void
    1879                 :      713749 : AbortStrongLockAcquire(void)
    1880                 :             : {
    1881                 :             :     uint32      fasthashcode;
    1882                 :      713749 :     LOCALLOCK  *locallock = StrongLockInProgress;
    1883                 :             : 
    1884         [ +  + ]:      713749 :     if (locallock == NULL)
    1885                 :      713536 :         return;
    1886                 :             : 
    1887                 :         213 :     fasthashcode = FastPathStrongLockHashPartition(locallock->hashcode);
    1888                 :             :     Assert(locallock->holdsStrongLockCount == true);
    1889                 :         213 :     SpinLockAcquire(&FastPathStrongRelationLocks->mutex);
    1890                 :             :     Assert(FastPathStrongRelationLocks->count[fasthashcode] > 0);
    1891                 :         213 :     FastPathStrongRelationLocks->count[fasthashcode]--;
    1892                 :         213 :     locallock->holdsStrongLockCount = false;
    1893                 :         213 :     StrongLockInProgress = NULL;
    1894                 :         213 :     SpinLockRelease(&FastPathStrongRelationLocks->mutex);
    1895                 :             : }
    1896                 :             : 
    1897                 :             : /*
    1898                 :             :  * GrantAwaitedLock -- call GrantLockLocal for the lock we are doing
    1899                 :             :  *      WaitOnLock on.
    1900                 :             :  *
    1901                 :             :  * proc.c needs this for the case where we are booted off the lock by
    1902                 :             :  * timeout, but discover that someone granted us the lock anyway.
    1903                 :             :  *
    1904                 :             :  * We could just export GrantLockLocal, but that would require including
    1905                 :             :  * resowner.h in lock.h, which creates circularity.
    1906                 :             :  */
    1907                 :             : void
    1908                 :           2 : GrantAwaitedLock(void)
    1909                 :             : {
    1910                 :           2 :     GrantLockLocal(awaitedLock, awaitedOwner);
    1911                 :           2 : }
    1912                 :             : 
    1913                 :             : /*
    1914                 :             :  * GetAwaitedLock -- Return the lock we're currently doing WaitOnLock on.
    1915                 :             :  */
    1916                 :             : LOCALLOCK *
    1917                 :      713024 : GetAwaitedLock(void)
    1918                 :             : {
    1919                 :      713024 :     return awaitedLock;
    1920                 :             : }
    1921                 :             : 
    1922                 :             : /*
    1923                 :             :  * ResetAwaitedLock -- Forget that we are waiting on a lock.
    1924                 :             :  */
    1925                 :             : void
    1926                 :          44 : ResetAwaitedLock(void)
    1927                 :             : {
    1928                 :          44 :     awaitedLock = NULL;
    1929                 :          44 : }
    1930                 :             : 
    1931                 :             : /*
    1932                 :             :  * MarkLockClear -- mark an acquired lock as "clear"
    1933                 :             :  *
    1934                 :             :  * This means that we know we have absorbed all sinval messages that other
    1935                 :             :  * sessions generated before we acquired this lock, and so we can confidently
    1936                 :             :  * assume we know about any catalog changes protected by this lock.
    1937                 :             :  */
    1938                 :             : void
    1939                 :    23863268 : MarkLockClear(LOCALLOCK *locallock)
    1940                 :             : {
    1941                 :             :     Assert(locallock->nLocks > 0);
    1942                 :    23863268 :     locallock->lockCleared = true;
    1943                 :    23863268 : }
    1944                 :             : 
    1945                 :             : /*
    1946                 :             :  * WaitOnLock -- wait to acquire a lock
    1947                 :             :  *
    1948                 :             :  * This is a wrapper around ProcSleep, with extra tracing and bookkeeping.
    1949                 :             :  */
    1950                 :             : static ProcWaitStatus
    1951                 :        1481 : WaitOnLock(LOCALLOCK *locallock, ResourceOwner owner)
    1952                 :             : {
    1953                 :             :     ProcWaitStatus result;
    1954                 :             :     ErrorContextCallback waiterrcontext;
    1955                 :             : 
    1956                 :             :     TRACE_POSTGRESQL_LOCK_WAIT_START(locallock->tag.lock.locktag_field1,
    1957                 :             :                                      locallock->tag.lock.locktag_field2,
    1958                 :             :                                      locallock->tag.lock.locktag_field3,
    1959                 :             :                                      locallock->tag.lock.locktag_field4,
    1960                 :             :                                      locallock->tag.lock.locktag_type,
    1961                 :             :                                      locallock->tag.mode);
    1962                 :             : 
    1963                 :             :     /* Setup error traceback support for ereport() */
    1964                 :        1481 :     waiterrcontext.callback = waitonlock_error_callback;
    1965                 :        1481 :     waiterrcontext.arg = locallock;
    1966                 :        1481 :     waiterrcontext.previous = error_context_stack;
    1967                 :        1481 :     error_context_stack = &waiterrcontext;
    1968                 :             : 
    1969                 :             :     /* adjust the process title to indicate that it's waiting */
    1970                 :        1481 :     set_ps_display_suffix("waiting");
    1971                 :             : 
    1972                 :             :     /*
    1973                 :             :      * Record the fact that we are waiting for a lock, so that
    1974                 :             :      * LockErrorCleanup will clean up if cancel/die happens.
    1975                 :             :      */
    1976                 :        1481 :     awaitedLock = locallock;
    1977                 :        1481 :     awaitedOwner = owner;
    1978                 :             : 
    1979                 :             :     /*
    1980                 :             :      * NOTE: Think not to put any shared-state cleanup after the call to
    1981                 :             :      * ProcSleep, in either the normal or failure path.  The lock state must
    1982                 :             :      * be fully set by the lock grantor, or by CheckDeadLock if we give up
    1983                 :             :      * waiting for the lock.  This is necessary because of the possibility
    1984                 :             :      * that a cancel/die interrupt will interrupt ProcSleep after someone else
    1985                 :             :      * grants us the lock, but before we've noticed it. Hence, after granting,
    1986                 :             :      * the locktable state must fully reflect the fact that we own the lock;
    1987                 :             :      * we can't do additional work on return.
    1988                 :             :      *
    1989                 :             :      * We can and do use a PG_TRY block to try to clean up after failure, but
    1990                 :             :      * this still has a major limitation: elog(FATAL) can occur while waiting
    1991                 :             :      * (eg, a "die" interrupt), and then control won't come back here. So all
    1992                 :             :      * cleanup of essential state should happen in LockErrorCleanup, not here.
    1993                 :             :      * We can use PG_TRY to clear the "waiting" status flags, since doing that
    1994                 :             :      * is unimportant if the process exits.
    1995                 :             :      */
    1996         [ +  + ]:        1481 :     PG_TRY();
    1997                 :             :     {
    1998                 :        1481 :         result = ProcSleep(locallock);
    1999                 :             :     }
    2000                 :          39 :     PG_CATCH();
    2001                 :             :     {
    2002                 :             :         /* In this path, awaitedLock remains set until LockErrorCleanup */
    2003                 :             : 
    2004                 :             :         /* reset ps display to remove the suffix */
    2005                 :          39 :         set_ps_display_remove_suffix();
    2006                 :             : 
    2007                 :             :         /* and propagate the error */
    2008                 :          39 :         PG_RE_THROW();
    2009                 :             :     }
    2010         [ -  + ]:        1436 :     PG_END_TRY();
    2011                 :             : 
    2012                 :             :     /*
    2013                 :             :      * We no longer want LockErrorCleanup to do anything.
    2014                 :             :      */
    2015                 :        1436 :     awaitedLock = NULL;
    2016                 :             : 
    2017                 :             :     /* reset ps display to remove the suffix */
    2018                 :        1436 :     set_ps_display_remove_suffix();
    2019                 :             : 
    2020                 :        1436 :     error_context_stack = waiterrcontext.previous;
    2021                 :             : 
    2022                 :             :     TRACE_POSTGRESQL_LOCK_WAIT_DONE(locallock->tag.lock.locktag_field1,
    2023                 :             :                                     locallock->tag.lock.locktag_field2,
    2024                 :             :                                     locallock->tag.lock.locktag_field3,
    2025                 :             :                                     locallock->tag.lock.locktag_field4,
    2026                 :             :                                     locallock->tag.lock.locktag_type,
    2027                 :             :                                     locallock->tag.mode);
    2028                 :             : 
    2029                 :        1436 :     return result;
    2030                 :             : }
    2031                 :             : 
    2032                 :             : /*
    2033                 :             :  * error context callback for failures in WaitOnLock
    2034                 :             :  *
    2035                 :             :  * We report which lock was being waited on, in the same style used in
    2036                 :             :  * deadlock reports.  This helps with lock timeout errors in particular.
    2037                 :             :  */
    2038                 :             : static void
    2039                 :         229 : waitonlock_error_callback(void *arg)
    2040                 :             : {
    2041                 :         229 :     LOCALLOCK  *locallock = (LOCALLOCK *) arg;
    2042                 :         229 :     const LOCKTAG *tag = &locallock->tag.lock;
    2043                 :         229 :     LOCKMODE    mode = locallock->tag.mode;
    2044                 :             :     StringInfoData locktagbuf;
    2045                 :             : 
    2046                 :         229 :     initStringInfo(&locktagbuf);
    2047                 :         229 :     DescribeLockTag(&locktagbuf, tag);
    2048                 :             : 
    2049                 :         458 :     errcontext("waiting for %s on %s",
    2050                 :         229 :                GetLockmodeName(tag->locktag_lockmethodid, mode),
    2051                 :             :                locktagbuf.data);
    2052                 :         229 : }
    2053                 :             : 
    2054                 :             : /*
    2055                 :             :  * Remove a proc from the wait-queue it is on (caller must know it is on one).
    2056                 :             :  * This is only used when the proc has failed to get the lock, so we set its
    2057                 :             :  * waitStatus to PROC_WAIT_STATUS_ERROR.
    2058                 :             :  *
    2059                 :             :  * Appropriate partition lock must be held by caller.  Also, caller is
    2060                 :             :  * responsible for signaling the proc if needed.
    2061                 :             :  *
    2062                 :             :  * NB: this does not clean up any locallock object that may exist for the lock.
    2063                 :             :  */
    2064                 :             : void
    2065                 :          47 : RemoveFromWaitQueue(PGPROC *proc, uint32 hashcode)
    2066                 :             : {
    2067                 :          47 :     LOCK       *waitLock = proc->waitLock;
    2068                 :          47 :     PROCLOCK   *proclock = proc->waitProcLock;
    2069                 :          47 :     LOCKMODE    lockmode = proc->waitLockMode;
    2070                 :          47 :     LOCKMETHODID lockmethodid = LOCK_LOCKMETHOD(*waitLock);
    2071                 :             : 
    2072                 :             :     /* Make sure proc is waiting */
    2073                 :             :     Assert(proc->waitStatus == PROC_WAIT_STATUS_WAITING);
    2074                 :             :     Assert(!dlist_node_is_detached(&proc->waitLink));
    2075                 :             :     Assert(waitLock);
    2076                 :             :     Assert(!dclist_is_empty(&waitLock->waitProcs));
    2077                 :             :     Assert(0 < lockmethodid && lockmethodid < lengthof(LockMethods));
    2078                 :             : 
    2079                 :             :     /* Remove proc from lock's wait queue */
    2080                 :          47 :     dclist_delete_from_thoroughly(&waitLock->waitProcs, &proc->waitLink);
    2081                 :             : 
    2082                 :             :     /* Undo increments of request counts by waiting process */
    2083                 :             :     Assert(waitLock->nRequested > 0);
    2084                 :             :     Assert(waitLock->nRequested > proc->waitLock->nGranted);
    2085                 :          47 :     waitLock->nRequested--;
    2086                 :             :     Assert(waitLock->requested[lockmode] > 0);
    2087                 :          47 :     waitLock->requested[lockmode]--;
    2088                 :             :     /* don't forget to clear waitMask bit if appropriate */
    2089         [ +  - ]:          47 :     if (waitLock->granted[lockmode] == waitLock->requested[lockmode])
    2090                 :          47 :         waitLock->waitMask &= LOCKBIT_OFF(lockmode);
    2091                 :             : 
    2092                 :             :     /* Clean up the proc's own state, and pass it the ok/fail signal */
    2093                 :          47 :     proc->waitLock = NULL;
    2094                 :          47 :     proc->waitProcLock = NULL;
    2095                 :          47 :     proc->waitStatus = PROC_WAIT_STATUS_ERROR;
    2096                 :             : 
    2097                 :             :     /*
    2098                 :             :      * Delete the proclock immediately if it represents no already-held locks.
    2099                 :             :      * (This must happen now because if the owner of the lock decides to
    2100                 :             :      * release it, and the requested/granted counts then go to zero,
    2101                 :             :      * LockRelease expects there to be no remaining proclocks.) Then see if
    2102                 :             :      * any other waiters for the lock can be woken up now.
    2103                 :             :      */
    2104                 :          47 :     CleanUpLock(waitLock, proclock,
    2105                 :          47 :                 LockMethods[lockmethodid], hashcode,
    2106                 :             :                 true);
    2107                 :          47 : }
    2108                 :             : 
    2109                 :             : /*
    2110                 :             :  * LockRelease -- look up 'locktag' and release one 'lockmode' lock on it.
    2111                 :             :  *      Release a session lock if 'sessionLock' is true, else release a
    2112                 :             :  *      regular transaction lock.
    2113                 :             :  *
    2114                 :             :  * Side Effects: find any waiting processes that are now wakable,
    2115                 :             :  *      grant them their requested locks and awaken them.
    2116                 :             :  *      (We have to grant the lock here to avoid a race between
    2117                 :             :  *      the waking process and any new process to
    2118                 :             :  *      come along and request the lock.)
    2119                 :             :  */
    2120                 :             : bool
    2121                 :    24871566 : LockRelease(const LOCKTAG *locktag, LOCKMODE lockmode, bool sessionLock)
    2122                 :             : {
    2123                 :    24871566 :     LOCKMETHODID lockmethodid = locktag->locktag_lockmethodid;
    2124                 :             :     LockMethod  lockMethodTable;
    2125                 :             :     LOCALLOCKTAG localtag;
    2126                 :             :     LOCALLOCK  *locallock;
    2127                 :             :     LOCK       *lock;
    2128                 :             :     PROCLOCK   *proclock;
    2129                 :             :     LWLock     *partitionLock;
    2130                 :             :     bool        wakeupNeeded;
    2131                 :             : 
    2132   [ +  -  -  + ]:    24871566 :     if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
    2133         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock method: %d", lockmethodid);
    2134                 :    24871566 :     lockMethodTable = LockMethods[lockmethodid];
    2135   [ +  -  -  + ]:    24871566 :     if (lockmode <= 0 || lockmode > lockMethodTable->numLockModes)
    2136         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock mode: %d", lockmode);
    2137                 :             : 
    2138                 :             : #ifdef LOCK_DEBUG
    2139                 :             :     if (LOCK_DEBUG_ENABLED(locktag))
    2140                 :             :         elog(LOG, "LockRelease: lock [%u,%u] %s",
    2141                 :             :              locktag->locktag_field1, locktag->locktag_field2,
    2142                 :             :              lockMethodTable->lockModeNames[lockmode]);
    2143                 :             : #endif
    2144                 :             : 
    2145                 :             :     /*
    2146                 :             :      * Find the LOCALLOCK entry for this lock and lockmode
    2147                 :             :      */
    2148   [ +  -  -  +  :    24871566 :     MemSet(&localtag, 0, sizeof(localtag)); /* must clear padding */
          -  -  -  -  -  
                      - ]
    2149                 :    24871566 :     localtag.lock = *locktag;
    2150                 :    24871566 :     localtag.mode = lockmode;
    2151                 :             : 
    2152                 :    24871566 :     locallock = (LOCALLOCK *) hash_search(LockMethodLocalHash,
    2153                 :             :                                           &localtag,
    2154                 :             :                                           HASH_FIND, NULL);
    2155                 :             : 
    2156                 :             :     /*
    2157                 :             :      * let the caller print its own error message, too. Do not ereport(ERROR).
    2158                 :             :      */
    2159   [ +  +  -  + ]:    24871566 :     if (!locallock || locallock->nLocks <= 0)
    2160                 :             :     {
    2161         [ +  - ]:          17 :         elog(WARNING, "you don't own a lock of type %s",
    2162                 :             :              lockMethodTable->lockModeNames[lockmode]);
    2163                 :          17 :         return false;
    2164                 :             :     }
    2165                 :             : 
    2166                 :             :     /*
    2167                 :             :      * Decrease the count for the resource owner.
    2168                 :             :      */
    2169                 :             :     {
    2170                 :    24871549 :         LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
    2171                 :             :         ResourceOwner owner;
    2172                 :             :         int         i;
    2173                 :             : 
    2174                 :             :         /* Identify owner for lock */
    2175         [ +  + ]:    24871549 :         if (sessionLock)
    2176                 :      161063 :             owner = NULL;
    2177                 :             :         else
    2178                 :    24710486 :             owner = CurrentResourceOwner;
    2179                 :             : 
    2180         [ +  + ]:    24872788 :         for (i = locallock->numLockOwners - 1; i >= 0; i--)
    2181                 :             :         {
    2182         [ +  + ]:    24872772 :             if (lockOwners[i].owner == owner)
    2183                 :             :             {
    2184                 :             :                 Assert(lockOwners[i].nLocks > 0);
    2185         [ +  + ]:    24871533 :                 if (--lockOwners[i].nLocks == 0)
    2186                 :             :                 {
    2187         [ +  + ]:    24100077 :                     if (owner != NULL)
    2188                 :    23939053 :                         ResourceOwnerForgetLock(owner, locallock);
    2189                 :             :                     /* compact out unused slot */
    2190                 :    24100077 :                     locallock->numLockOwners--;
    2191         [ +  + ]:    24100077 :                     if (i < locallock->numLockOwners)
    2192                 :          89 :                         lockOwners[i] = lockOwners[locallock->numLockOwners];
    2193                 :             :                 }
    2194                 :    24871533 :                 break;
    2195                 :             :             }
    2196                 :             :         }
    2197         [ +  + ]:    24871549 :         if (i < 0)
    2198                 :             :         {
    2199                 :             :             /* don't release a lock belonging to another owner */
    2200         [ +  - ]:          16 :             elog(WARNING, "you don't own a lock of type %s",
    2201                 :             :                  lockMethodTable->lockModeNames[lockmode]);
    2202                 :          16 :             return false;
    2203                 :             :         }
    2204                 :             :     }
    2205                 :             : 
    2206                 :             :     /*
    2207                 :             :      * Decrease the total local count.  If we're still holding the lock, we're
    2208                 :             :      * done.
    2209                 :             :      */
    2210                 :    24871533 :     locallock->nLocks--;
    2211                 :             : 
    2212         [ +  + ]:    24871533 :     if (locallock->nLocks > 0)
    2213                 :     1660312 :         return true;
    2214                 :             : 
    2215                 :             :     /*
    2216                 :             :      * At this point we can no longer suppose we are clear of invalidation
    2217                 :             :      * messages related to this lock.  Although we'll delete the LOCALLOCK
    2218                 :             :      * object before any intentional return from this routine, it seems worth
    2219                 :             :      * the trouble to explicitly reset lockCleared right now, just in case
    2220                 :             :      * some error prevents us from deleting the LOCALLOCK.
    2221                 :             :      */
    2222                 :    23211221 :     locallock->lockCleared = false;
    2223                 :             : 
    2224                 :             :     /* Attempt fast release of any lock eligible for the fast path. */
    2225   [ +  +  +  +  :    23211221 :     if (EligibleForRelationFastPath(locktag, lockmode) &&
          +  +  +  +  +  
                      + ]
    2226         [ +  + ]:    21415194 :         FastPathLocalUseCounts[FAST_PATH_REL_GROUP(locktag->locktag_field2)] > 0)
    2227                 :             :     {
    2228                 :             :         bool        released;
    2229                 :             : 
    2230                 :             :         /*
    2231                 :             :          * We might not find the lock here, even if we originally entered it
    2232                 :             :          * here.  Another backend may have moved it to the main table.
    2233                 :             :          */
    2234                 :    21109870 :         LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
    2235                 :    21109870 :         released = FastPathUnGrantRelationLock(locktag->locktag_field2,
    2236                 :             :                                                lockmode);
    2237                 :    21109870 :         LWLockRelease(&MyProc->fpInfoLock);
    2238         [ +  + ]:    21109870 :         if (released)
    2239                 :             :         {
    2240                 :    20990962 :             RemoveLocalLock(locallock);
    2241                 :    20990962 :             return true;
    2242                 :             :         }
    2243                 :             :     }
    2244                 :             : 
    2245                 :             :     /*
    2246                 :             :      * Otherwise we've got to mess with the shared lock table.
    2247                 :             :      */
    2248                 :     2220259 :     partitionLock = LockHashPartitionLock(locallock->hashcode);
    2249                 :             : 
    2250                 :     2220259 :     LWLockAcquire(partitionLock, LW_EXCLUSIVE);
    2251                 :             : 
    2252                 :             :     /*
    2253                 :             :      * Normally, we don't need to re-find the lock or proclock, since we kept
    2254                 :             :      * their addresses in the locallock table, and they couldn't have been
    2255                 :             :      * removed while we were holding a lock on them.  But it's possible that
    2256                 :             :      * the lock was taken fast-path and has since been moved to the main hash
    2257                 :             :      * table by another backend, in which case we will need to look up the
    2258                 :             :      * objects here.  We assume the lock field is NULL if so.
    2259                 :             :      */
    2260                 :     2220259 :     lock = locallock->lock;
    2261         [ +  + ]:     2220259 :     if (!lock)
    2262                 :             :     {
    2263                 :             :         PROCLOCKTAG proclocktag;
    2264                 :             : 
    2265                 :             :         Assert(EligibleForRelationFastPath(locktag, lockmode));
    2266                 :           7 :         lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
    2267                 :             :                                                     locktag,
    2268                 :             :                                                     locallock->hashcode,
    2269                 :             :                                                     HASH_FIND,
    2270                 :             :                                                     NULL);
    2271         [ -  + ]:           7 :         if (!lock)
    2272         [ #  # ]:           0 :             elog(ERROR, "failed to re-find shared lock object");
    2273                 :           7 :         locallock->lock = lock;
    2274                 :             : 
    2275                 :           7 :         proclocktag.myLock = lock;
    2276                 :           7 :         proclocktag.myProc = MyProc;
    2277                 :           7 :         locallock->proclock = (PROCLOCK *) hash_search(LockMethodProcLockHash,
    2278                 :             :                                                        &proclocktag,
    2279                 :             :                                                        HASH_FIND,
    2280                 :             :                                                        NULL);
    2281         [ -  + ]:           7 :         if (!locallock->proclock)
    2282         [ #  # ]:           0 :             elog(ERROR, "failed to re-find shared proclock object");
    2283                 :             :     }
    2284                 :             :     LOCK_PRINT("LockRelease: found", lock, lockmode);
    2285                 :     2220259 :     proclock = locallock->proclock;
    2286                 :             :     PROCLOCK_PRINT("LockRelease: found", proclock);
    2287                 :             : 
    2288                 :             :     /*
    2289                 :             :      * Double-check that we are actually holding a lock of the type we want to
    2290                 :             :      * release.
    2291                 :             :      */
    2292         [ -  + ]:     2220259 :     if (!(proclock->holdMask & LOCKBIT_ON(lockmode)))
    2293                 :             :     {
    2294                 :             :         PROCLOCK_PRINT("LockRelease: WRONGTYPE", proclock);
    2295                 :           0 :         LWLockRelease(partitionLock);
    2296         [ #  # ]:           0 :         elog(WARNING, "you don't own a lock of type %s",
    2297                 :             :              lockMethodTable->lockModeNames[lockmode]);
    2298                 :           0 :         RemoveLocalLock(locallock);
    2299                 :           0 :         return false;
    2300                 :             :     }
    2301                 :             : 
    2302                 :             :     /*
    2303                 :             :      * Do the releasing.  CleanUpLock will waken any now-wakable waiters.
    2304                 :             :      */
    2305                 :     2220259 :     wakeupNeeded = UnGrantLock(lock, lockmode, proclock, lockMethodTable);
    2306                 :             : 
    2307                 :     2220259 :     CleanUpLock(lock, proclock,
    2308                 :             :                 lockMethodTable, locallock->hashcode,
    2309                 :             :                 wakeupNeeded);
    2310                 :             : 
    2311                 :     2220259 :     LWLockRelease(partitionLock);
    2312                 :             : 
    2313                 :     2220259 :     RemoveLocalLock(locallock);
    2314                 :     2220259 :     return true;
    2315                 :             : }
    2316                 :             : 
    2317                 :             : /*
    2318                 :             :  * LockReleaseAll -- Release all locks of the specified lock method that
    2319                 :             :  *      are held by the current process.
    2320                 :             :  *
    2321                 :             :  * Well, not necessarily *all* locks.  The available behaviors are:
    2322                 :             :  *      allLocks == true: release all locks including session locks.
    2323                 :             :  *      allLocks == false: release all non-session locks.
    2324                 :             :  */
    2325                 :             : void
    2326                 :     1362544 : LockReleaseAll(LOCKMETHODID lockmethodid, bool allLocks)
    2327                 :             : {
    2328                 :             :     HASH_SEQ_STATUS status;
    2329                 :             :     LockMethod  lockMethodTable;
    2330                 :             :     int         i,
    2331                 :             :                 numLockModes;
    2332                 :             :     LOCALLOCK  *locallock;
    2333                 :             :     LOCK       *lock;
    2334                 :             :     int         partition;
    2335                 :     1362544 :     bool        have_fast_path_lwlock = false;
    2336                 :             : 
    2337   [ +  -  -  + ]:     1362544 :     if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
    2338         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock method: %d", lockmethodid);
    2339                 :     1362544 :     lockMethodTable = LockMethods[lockmethodid];
    2340                 :             : 
    2341                 :             : #ifdef LOCK_DEBUG
    2342                 :             :     if (*(lockMethodTable->trace_flag))
    2343                 :             :         elog(LOG, "LockReleaseAll: lockmethod=%d", lockmethodid);
    2344                 :             : #endif
    2345                 :             : 
    2346                 :             :     /*
    2347                 :             :      * Get rid of our fast-path VXID lock, if appropriate.  Note that this is
    2348                 :             :      * the only way that the lock we hold on our own VXID can ever get
    2349                 :             :      * released: it is always and only released when a toplevel transaction
    2350                 :             :      * ends.
    2351                 :             :      */
    2352         [ +  + ]:     1362544 :     if (lockmethodid == DEFAULT_LOCKMETHOD)
    2353                 :      671169 :         VirtualXactLockTableCleanup();
    2354                 :             : 
    2355                 :     1362544 :     numLockModes = lockMethodTable->numLockModes;
    2356                 :             : 
    2357                 :             :     /*
    2358                 :             :      * First we run through the locallock table and get rid of unwanted
    2359                 :             :      * entries, then we scan the process's proclocks and get rid of those. We
    2360                 :             :      * do this separately because we may have multiple locallock entries
    2361                 :             :      * pointing to the same proclock, and we daren't end up with any dangling
    2362                 :             :      * pointers.  Fast-path locks are cleaned up during the locallock table
    2363                 :             :      * scan, though.
    2364                 :             :      */
    2365                 :     1362544 :     hash_seq_init(&status, LockMethodLocalHash);
    2366                 :             : 
    2367         [ +  + ]:     3299717 :     while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
    2368                 :             :     {
    2369                 :             :         /*
    2370                 :             :          * If the LOCALLOCK entry is unused, something must've gone wrong
    2371                 :             :          * while trying to acquire this lock.  Just forget the local entry.
    2372                 :             :          */
    2373         [ +  + ]:     1937173 :         if (locallock->nLocks == 0)
    2374                 :             :         {
    2375                 :          48 :             RemoveLocalLock(locallock);
    2376                 :          48 :             continue;
    2377                 :             :         }
    2378                 :             : 
    2379                 :             :         /* Ignore items that are not of the lockmethod to be removed */
    2380         [ +  + ]:     1937125 :         if (LOCALLOCK_LOCKMETHOD(*locallock) != lockmethodid)
    2381                 :      149780 :             continue;
    2382                 :             : 
    2383                 :             :         /*
    2384                 :             :          * If we are asked to release all locks, we can just zap the entry.
    2385                 :             :          * Otherwise, must scan to see if there are session locks. We assume
    2386                 :             :          * there is at most one lockOwners entry for session locks.
    2387                 :             :          */
    2388         [ +  + ]:     1787345 :         if (!allLocks)
    2389                 :             :         {
    2390                 :     1679847 :             LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
    2391                 :             : 
    2392                 :             :             /* If session lock is above array position 0, move it down to 0 */
    2393         [ +  + ]:     3495716 :             for (i = 0; i < locallock->numLockOwners; i++)
    2394                 :             :             {
    2395         [ +  + ]:     1815869 :                 if (lockOwners[i].owner == NULL)
    2396                 :      149461 :                     lockOwners[0] = lockOwners[i];
    2397                 :             :                 else
    2398                 :     1666408 :                     ResourceOwnerForgetLock(lockOwners[i].owner, locallock);
    2399                 :             :             }
    2400                 :             : 
    2401         [ +  - ]:     1679847 :             if (locallock->numLockOwners > 0 &&
    2402         [ +  + ]:     1679847 :                 lockOwners[0].owner == NULL &&
    2403         [ +  - ]:      149461 :                 lockOwners[0].nLocks > 0)
    2404                 :             :             {
    2405                 :             :                 /* Fix the locallock to show just the session locks */
    2406                 :      149461 :                 locallock->nLocks = lockOwners[0].nLocks;
    2407                 :      149461 :                 locallock->numLockOwners = 1;
    2408                 :             :                 /* We aren't deleting this locallock, so done */
    2409                 :      149461 :                 continue;
    2410                 :             :             }
    2411                 :             :             else
    2412                 :     1530386 :                 locallock->numLockOwners = 0;
    2413                 :             :         }
    2414                 :             : 
    2415                 :             : #ifdef USE_ASSERT_CHECKING
    2416                 :             : 
    2417                 :             :         /*
    2418                 :             :          * Tuple locks are currently held only for short durations within a
    2419                 :             :          * transaction. Check that we didn't forget to release one.
    2420                 :             :          */
    2421                 :             :         if (LOCALLOCK_LOCKTAG(*locallock) == LOCKTAG_TUPLE && !allLocks)
    2422                 :             :             elog(WARNING, "tuple lock held at commit");
    2423                 :             : #endif
    2424                 :             : 
    2425                 :             :         /*
    2426                 :             :          * If the lock or proclock pointers are NULL, this lock was taken via
    2427                 :             :          * the relation fast-path (and is not known to have been transferred).
    2428                 :             :          */
    2429   [ +  +  -  + ]:     1637884 :         if (locallock->proclock == NULL || locallock->lock == NULL)
    2430                 :        1601 :         {
    2431                 :      837232 :             LOCKMODE    lockmode = locallock->tag.mode;
    2432                 :             :             Oid         relid;
    2433                 :             : 
    2434                 :             :             /* Verify that a fast-path lock is what we've got. */
    2435   [ +  -  +  -  :      837232 :             if (!EligibleForRelationFastPath(&locallock->tag.lock, lockmode))
          +  -  +  -  -  
                      + ]
    2436         [ #  # ]:           0 :                 elog(PANIC, "locallock table corrupted");
    2437                 :             : 
    2438                 :             :             /*
    2439                 :             :              * If we don't currently hold the LWLock that protects our
    2440                 :             :              * fast-path data structures, we must acquire it before attempting
    2441                 :             :              * to release the lock via the fast-path.  We will continue to
    2442                 :             :              * hold the LWLock until we're done scanning the locallock table,
    2443                 :             :              * unless we hit a transferred fast-path lock.  (XXX is this
    2444                 :             :              * really such a good idea?  There could be a lot of entries ...)
    2445                 :             :              */
    2446         [ +  + ]:      837232 :             if (!have_fast_path_lwlock)
    2447                 :             :             {
    2448                 :      291759 :                 LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
    2449                 :      291759 :                 have_fast_path_lwlock = true;
    2450                 :             :             }
    2451                 :             : 
    2452                 :             :             /* Attempt fast-path release. */
    2453                 :      837232 :             relid = locallock->tag.lock.locktag_field2;
    2454         [ +  + ]:      837232 :             if (FastPathUnGrantRelationLock(relid, lockmode))
    2455                 :             :             {
    2456                 :      835631 :                 RemoveLocalLock(locallock);
    2457                 :      835631 :                 continue;
    2458                 :             :             }
    2459                 :             : 
    2460                 :             :             /*
    2461                 :             :              * Our lock, originally taken via the fast path, has been
    2462                 :             :              * transferred to the main lock table.  That's going to require
    2463                 :             :              * some extra work, so release our fast-path lock before starting.
    2464                 :             :              */
    2465                 :        1601 :             LWLockRelease(&MyProc->fpInfoLock);
    2466                 :        1601 :             have_fast_path_lwlock = false;
    2467                 :             : 
    2468                 :             :             /*
    2469                 :             :              * Now dump the lock.  We haven't got a pointer to the LOCK or
    2470                 :             :              * PROCLOCK in this case, so we have to handle this a bit
    2471                 :             :              * differently than a normal lock release.  Unfortunately, this
    2472                 :             :              * requires an extra LWLock acquire-and-release cycle on the
    2473                 :             :              * partitionLock, but hopefully it shouldn't happen often.
    2474                 :             :              */
    2475                 :        1601 :             LockRefindAndRelease(lockMethodTable, MyProc,
    2476                 :             :                                  &locallock->tag.lock, lockmode, false);
    2477                 :        1601 :             RemoveLocalLock(locallock);
    2478                 :        1601 :             continue;
    2479                 :             :         }
    2480                 :             : 
    2481                 :             :         /* Mark the proclock to show we need to release this lockmode */
    2482         [ +  - ]:      800652 :         if (locallock->nLocks > 0)
    2483                 :      800652 :             locallock->proclock->releaseMask |= LOCKBIT_ON(locallock->tag.mode);
    2484                 :             : 
    2485                 :             :         /* And remove the locallock hashtable entry */
    2486                 :      800652 :         RemoveLocalLock(locallock);
    2487                 :             :     }
    2488                 :             : 
    2489                 :             :     /* Done with the fast-path data structures */
    2490         [ +  + ]:     1362544 :     if (have_fast_path_lwlock)
    2491                 :      290158 :         LWLockRelease(&MyProc->fpInfoLock);
    2492                 :             : 
    2493                 :             :     /*
    2494                 :             :      * Now, scan each lock partition separately.
    2495                 :             :      */
    2496         [ +  + ]:    23163248 :     for (partition = 0; partition < NUM_LOCK_PARTITIONS; partition++)
    2497                 :             :     {
    2498                 :             :         LWLock     *partitionLock;
    2499                 :    21800704 :         dlist_head *procLocks = &MyProc->myProcLocks[partition];
    2500                 :             :         dlist_mutable_iter proclock_iter;
    2501                 :             : 
    2502                 :    21800704 :         partitionLock = LockHashPartitionLockByIndex(partition);
    2503                 :             : 
    2504                 :             :         /*
    2505                 :             :          * If the proclock list for this partition is empty, we can skip
    2506                 :             :          * acquiring the partition lock.  This optimization is trickier than
    2507                 :             :          * it looks, because another backend could be in process of adding
    2508                 :             :          * something to our proclock list due to promoting one of our
    2509                 :             :          * fast-path locks.  However, any such lock must be one that we
    2510                 :             :          * decided not to delete above, so it's okay to skip it again now;
    2511                 :             :          * we'd just decide not to delete it again.  We must, however, be
    2512                 :             :          * careful to re-fetch the list header once we've acquired the
    2513                 :             :          * partition lock, to be sure we have a valid, up-to-date pointer.
    2514                 :             :          * (There is probably no significant risk if pointer fetch/store is
    2515                 :             :          * atomic, but we don't wish to assume that.)
    2516                 :             :          *
    2517                 :             :          * XXX This argument assumes that the locallock table correctly
    2518                 :             :          * represents all of our fast-path locks.  While allLocks mode
    2519                 :             :          * guarantees to clean up all of our normal locks regardless of the
    2520                 :             :          * locallock situation, we lose that guarantee for fast-path locks.
    2521                 :             :          * This is not ideal.
    2522                 :             :          */
    2523         [ +  + ]:    21800704 :         if (dlist_is_empty(procLocks))
    2524                 :    20916151 :             continue;           /* needn't examine this partition */
    2525                 :             : 
    2526                 :      884553 :         LWLockAcquire(partitionLock, LW_EXCLUSIVE);
    2527                 :             : 
    2528   [ +  -  +  + ]:     1935153 :         dlist_foreach_modify(proclock_iter, procLocks)
    2529                 :             :         {
    2530                 :     1050600 :             PROCLOCK   *proclock = dlist_container(PROCLOCK, procLink, proclock_iter.cur);
    2531                 :     1050600 :             bool        wakeupNeeded = false;
    2532                 :             : 
    2533                 :             :             Assert(proclock->tag.myProc == MyProc);
    2534                 :             : 
    2535                 :     1050600 :             lock = proclock->tag.myLock;
    2536                 :             : 
    2537                 :             :             /* Ignore items that are not of the lockmethod to be removed */
    2538         [ +  + ]:     1050600 :             if (LOCK_LOCKMETHOD(*lock) != lockmethodid)
    2539                 :      149779 :                 continue;
    2540                 :             : 
    2541                 :             :             /*
    2542                 :             :              * In allLocks mode, force release of all locks even if locallock
    2543                 :             :              * table had problems
    2544                 :             :              */
    2545         [ +  + ]:      900821 :             if (allLocks)
    2546                 :       46666 :                 proclock->releaseMask = proclock->holdMask;
    2547                 :             :             else
    2548                 :             :                 Assert((proclock->releaseMask & ~proclock->holdMask) == 0);
    2549                 :             : 
    2550                 :             :             /*
    2551                 :             :              * Ignore items that have nothing to be released, unless they have
    2552                 :             :              * holdMask == 0 and are therefore recyclable
    2553                 :             :              */
    2554   [ +  +  +  - ]:      900821 :             if (proclock->releaseMask == 0 && proclock->holdMask != 0)
    2555                 :      148547 :                 continue;
    2556                 :             : 
    2557                 :             :             PROCLOCK_PRINT("LockReleaseAll", proclock);
    2558                 :             :             LOCK_PRINT("LockReleaseAll", lock, 0);
    2559                 :             :             Assert(lock->nRequested >= 0);
    2560                 :             :             Assert(lock->nGranted >= 0);
    2561                 :             :             Assert(lock->nGranted <= lock->nRequested);
    2562                 :             :             Assert((proclock->holdMask & ~lock->grantMask) == 0);
    2563                 :             : 
    2564                 :             :             /*
    2565                 :             :              * Release the previously-marked lock modes
    2566                 :             :              */
    2567         [ +  + ]:     6770466 :             for (i = 1; i <= numLockModes; i++)
    2568                 :             :             {
    2569         [ +  + ]:     6018192 :                 if (proclock->releaseMask & LOCKBIT_ON(i))
    2570                 :      800653 :                     wakeupNeeded |= UnGrantLock(lock, i, proclock,
    2571                 :             :                                                 lockMethodTable);
    2572                 :             :             }
    2573                 :             :             Assert((lock->nRequested >= 0) && (lock->nGranted >= 0));
    2574                 :             :             Assert(lock->nGranted <= lock->nRequested);
    2575                 :             :             LOCK_PRINT("LockReleaseAll: updated", lock, 0);
    2576                 :             : 
    2577                 :      752274 :             proclock->releaseMask = 0;
    2578                 :             : 
    2579                 :             :             /* CleanUpLock will wake up waiters if needed. */
    2580                 :      752274 :             CleanUpLock(lock, proclock,
    2581                 :             :                         lockMethodTable,
    2582                 :      752274 :                         LockTagHashCode(&lock->tag),
    2583                 :             :                         wakeupNeeded);
    2584                 :             :         }                       /* loop over PROCLOCKs within this partition */
    2585                 :             : 
    2586                 :      884553 :         LWLockRelease(partitionLock);
    2587                 :             :     }                           /* loop over partitions */
    2588                 :             : 
    2589                 :             : #ifdef LOCK_DEBUG
    2590                 :             :     if (*(lockMethodTable->trace_flag))
    2591                 :             :         elog(LOG, "LockReleaseAll done");
    2592                 :             : #endif
    2593                 :     1362544 : }
    2594                 :             : 
    2595                 :             : /*
    2596                 :             :  * LockReleaseSession -- Release all session locks of the specified lock method
    2597                 :             :  *      that are held by the current process.
    2598                 :             :  */
    2599                 :             : void
    2600                 :         122 : LockReleaseSession(LOCKMETHODID lockmethodid)
    2601                 :             : {
    2602                 :             :     HASH_SEQ_STATUS status;
    2603                 :             :     LOCALLOCK  *locallock;
    2604                 :             : 
    2605   [ +  -  -  + ]:         122 :     if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
    2606         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock method: %d", lockmethodid);
    2607                 :             : 
    2608                 :         122 :     hash_seq_init(&status, LockMethodLocalHash);
    2609                 :             : 
    2610         [ +  + ]:         242 :     while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
    2611                 :             :     {
    2612                 :             :         /* Ignore items that are not of the specified lock method */
    2613         [ +  + ]:         120 :         if (LOCALLOCK_LOCKMETHOD(*locallock) != lockmethodid)
    2614                 :          11 :             continue;
    2615                 :             : 
    2616                 :         109 :         ReleaseLockIfHeld(locallock, true);
    2617                 :             :     }
    2618                 :         122 : }
    2619                 :             : 
    2620                 :             : /*
    2621                 :             :  * LockReleaseCurrentOwner
    2622                 :             :  *      Release all locks belonging to CurrentResourceOwner
    2623                 :             :  *
    2624                 :             :  * If the caller knows what those locks are, it can pass them as an array.
    2625                 :             :  * That speeds up the call significantly, when a lot of locks are held.
    2626                 :             :  * Otherwise, pass NULL for locallocks, and we'll traverse through our hash
    2627                 :             :  * table to find them.
    2628                 :             :  */
    2629                 :             : void
    2630                 :        6332 : LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks)
    2631                 :             : {
    2632         [ +  + ]:        6332 :     if (locallocks == NULL)
    2633                 :             :     {
    2634                 :             :         HASH_SEQ_STATUS status;
    2635                 :             :         LOCALLOCK  *locallock;
    2636                 :             : 
    2637                 :           9 :         hash_seq_init(&status, LockMethodLocalHash);
    2638                 :             : 
    2639         [ +  + ]:         647 :         while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
    2640                 :         638 :             ReleaseLockIfHeld(locallock, false);
    2641                 :             :     }
    2642                 :             :     else
    2643                 :             :     {
    2644                 :             :         int         i;
    2645                 :             : 
    2646         [ +  + ]:        9815 :         for (i = nlocks - 1; i >= 0; i--)
    2647                 :        3492 :             ReleaseLockIfHeld(locallocks[i], false);
    2648                 :             :     }
    2649                 :        6332 : }
    2650                 :             : 
    2651                 :             : /*
    2652                 :             :  * ReleaseLockIfHeld
    2653                 :             :  *      Release any session-level locks on this lockable object if sessionLock
    2654                 :             :  *      is true; else, release any locks held by CurrentResourceOwner.
    2655                 :             :  *
    2656                 :             :  * It is tempting to pass this a ResourceOwner pointer (or NULL for session
    2657                 :             :  * locks), but without refactoring LockRelease() we cannot support releasing
    2658                 :             :  * locks belonging to resource owners other than CurrentResourceOwner.
    2659                 :             :  * If we were to refactor, it'd be a good idea to fix it so we don't have to
    2660                 :             :  * do a hashtable lookup of the locallock, too.  However, currently this
    2661                 :             :  * function isn't used heavily enough to justify refactoring for its
    2662                 :             :  * convenience.
    2663                 :             :  */
    2664                 :             : static void
    2665                 :        4239 : ReleaseLockIfHeld(LOCALLOCK *locallock, bool sessionLock)
    2666                 :             : {
    2667                 :             :     ResourceOwner owner;
    2668                 :             :     LOCALLOCKOWNER *lockOwners;
    2669                 :             :     int         i;
    2670                 :             : 
    2671                 :             :     /* Identify owner for lock (must match LockRelease!) */
    2672         [ +  + ]:        4239 :     if (sessionLock)
    2673                 :         109 :         owner = NULL;
    2674                 :             :     else
    2675                 :        4130 :         owner = CurrentResourceOwner;
    2676                 :             : 
    2677                 :             :     /* Scan to see if there are any locks belonging to the target owner */
    2678                 :        4239 :     lockOwners = locallock->lockOwners;
    2679         [ +  + ]:        4708 :     for (i = locallock->numLockOwners - 1; i >= 0; i--)
    2680                 :             :     {
    2681         [ +  + ]:        4239 :         if (lockOwners[i].owner == owner)
    2682                 :             :         {
    2683                 :             :             Assert(lockOwners[i].nLocks > 0);
    2684         [ +  + ]:        3770 :             if (lockOwners[i].nLocks < locallock->nLocks)
    2685                 :             :             {
    2686                 :             :                 /*
    2687                 :             :                  * We will still hold this lock after forgetting this
    2688                 :             :                  * ResourceOwner.
    2689                 :             :                  */
    2690                 :         977 :                 locallock->nLocks -= lockOwners[i].nLocks;
    2691                 :             :                 /* compact out unused slot */
    2692                 :         977 :                 locallock->numLockOwners--;
    2693         [ +  - ]:         977 :                 if (owner != NULL)
    2694                 :         977 :                     ResourceOwnerForgetLock(owner, locallock);
    2695         [ -  + ]:         977 :                 if (i < locallock->numLockOwners)
    2696                 :           0 :                     lockOwners[i] = lockOwners[locallock->numLockOwners];
    2697                 :             :             }
    2698                 :             :             else
    2699                 :             :             {
    2700                 :             :                 Assert(lockOwners[i].nLocks == locallock->nLocks);
    2701                 :             :                 /* We want to call LockRelease just once */
    2702                 :        2793 :                 lockOwners[i].nLocks = 1;
    2703                 :        2793 :                 locallock->nLocks = 1;
    2704         [ -  + ]:        2793 :                 if (!LockRelease(&locallock->tag.lock,
    2705                 :             :                                  locallock->tag.mode,
    2706                 :             :                                  sessionLock))
    2707         [ #  # ]:           0 :                     elog(WARNING, "ReleaseLockIfHeld: failed??");
    2708                 :             :             }
    2709                 :        3770 :             break;
    2710                 :             :         }
    2711                 :             :     }
    2712                 :        4239 : }
    2713                 :             : 
    2714                 :             : /*
    2715                 :             :  * LockReassignCurrentOwner
    2716                 :             :  *      Reassign all locks belonging to CurrentResourceOwner to belong
    2717                 :             :  *      to its parent resource owner.
    2718                 :             :  *
    2719                 :             :  * If the caller knows what those locks are, it can pass them as an array.
    2720                 :             :  * That speeds up the call significantly, when a lot of locks are held
    2721                 :             :  * (e.g pg_dump with a large schema).  Otherwise, pass NULL for locallocks,
    2722                 :             :  * and we'll traverse through our hash table to find them.
    2723                 :             :  */
    2724                 :             : void
    2725                 :      449240 : LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks)
    2726                 :             : {
    2727                 :      449240 :     ResourceOwner parent = ResourceOwnerGetParent(CurrentResourceOwner);
    2728                 :             : 
    2729                 :             :     Assert(parent != NULL);
    2730                 :             : 
    2731         [ +  + ]:      449240 :     if (locallocks == NULL)
    2732                 :             :     {
    2733                 :             :         HASH_SEQ_STATUS status;
    2734                 :             :         LOCALLOCK  *locallock;
    2735                 :             : 
    2736                 :        8033 :         hash_seq_init(&status, LockMethodLocalHash);
    2737                 :             : 
    2738         [ +  + ]:      241461 :         while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
    2739                 :      233428 :             LockReassignOwner(locallock, parent);
    2740                 :             :     }
    2741                 :             :     else
    2742                 :             :     {
    2743                 :             :         int         i;
    2744                 :             : 
    2745         [ +  + ]:     1021325 :         for (i = nlocks - 1; i >= 0; i--)
    2746                 :      580118 :             LockReassignOwner(locallocks[i], parent);
    2747                 :             :     }
    2748                 :      449240 : }
    2749                 :             : 
    2750                 :             : /*
    2751                 :             :  * Subroutine of LockReassignCurrentOwner. Reassigns a given lock belonging to
    2752                 :             :  * CurrentResourceOwner to its parent.
    2753                 :             :  */
    2754                 :             : static void
    2755                 :      813546 : LockReassignOwner(LOCALLOCK *locallock, ResourceOwner parent)
    2756                 :             : {
    2757                 :             :     LOCALLOCKOWNER *lockOwners;
    2758                 :             :     int         i;
    2759                 :      813546 :     int         ic = -1;
    2760                 :      813546 :     int         ip = -1;
    2761                 :             : 
    2762                 :             :     /*
    2763                 :             :      * Scan to see if there are any locks belonging to current owner or its
    2764                 :             :      * parent
    2765                 :             :      */
    2766                 :      813546 :     lockOwners = locallock->lockOwners;
    2767         [ +  + ]:     1825452 :     for (i = locallock->numLockOwners - 1; i >= 0; i--)
    2768                 :             :     {
    2769         [ +  + ]:     1011906 :         if (lockOwners[i].owner == CurrentResourceOwner)
    2770                 :      752780 :             ic = i;
    2771         [ +  + ]:      259126 :         else if (lockOwners[i].owner == parent)
    2772                 :      215148 :             ip = i;
    2773                 :             :     }
    2774                 :             : 
    2775         [ +  + ]:      813546 :     if (ic < 0)
    2776                 :       60766 :         return;                 /* no current locks */
    2777                 :             : 
    2778         [ +  + ]:      752780 :     if (ip < 0)
    2779                 :             :     {
    2780                 :             :         /* Parent has no slot, so just give it the child's slot */
    2781                 :      598362 :         lockOwners[ic].owner = parent;
    2782                 :      598362 :         ResourceOwnerRememberLock(parent, locallock);
    2783                 :             :     }
    2784                 :             :     else
    2785                 :             :     {
    2786                 :             :         /* Merge child's count with parent's */
    2787                 :      154418 :         lockOwners[ip].nLocks += lockOwners[ic].nLocks;
    2788                 :             :         /* compact out unused slot */
    2789                 :      154418 :         locallock->numLockOwners--;
    2790         [ +  + ]:      154418 :         if (ic < locallock->numLockOwners)
    2791                 :         914 :             lockOwners[ic] = lockOwners[locallock->numLockOwners];
    2792                 :             :     }
    2793                 :      752780 :     ResourceOwnerForgetLock(CurrentResourceOwner, locallock);
    2794                 :             : }
    2795                 :             : 
    2796                 :             : /*
    2797                 :             :  * FastPathGrantRelationLock
    2798                 :             :  *      Grant lock using per-backend fast-path array, if there is space.
    2799                 :             :  */
    2800                 :             : static bool
    2801                 :    21828549 : FastPathGrantRelationLock(Oid relid, LOCKMODE lockmode)
    2802                 :             : {
    2803                 :             :     uint32      i;
    2804                 :    21828549 :     uint32      unused_slot = FastPathLockSlotsPerBackend();
    2805                 :             : 
    2806                 :             :     /* fast-path group the lock belongs to */
    2807                 :    21828549 :     uint32      group = FAST_PATH_REL_GROUP(relid);
    2808                 :             : 
    2809                 :             :     /* Scan for existing entry for this relid, remembering empty slot. */
    2810         [ +  + ]:   370293578 :     for (i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
    2811                 :             :     {
    2812                 :             :         /* index into the whole per-backend array */
    2813                 :   349119961 :         uint32      f = FAST_PATH_SLOT(group, i);
    2814                 :             : 
    2815         [ +  + ]:   349119961 :         if (FAST_PATH_GET_BITS(MyProc, f) == 0)
    2816                 :   341803330 :             unused_slot = f;
    2817         [ +  + ]:     7316631 :         else if (MyProc->fpRelId[f] == relid)
    2818                 :             :         {
    2819                 :             :             Assert(!FAST_PATH_CHECK_LOCKMODE(MyProc, f, lockmode));
    2820                 :      654932 :             FAST_PATH_SET_LOCKMODE(MyProc, f, lockmode);
    2821                 :      654932 :             return true;
    2822                 :             :         }
    2823                 :             :     }
    2824                 :             : 
    2825                 :             :     /* If no existing entry, use any empty slot. */
    2826         [ +  - ]:    21173617 :     if (unused_slot < FastPathLockSlotsPerBackend())
    2827                 :             :     {
    2828                 :    21173617 :         MyProc->fpRelId[unused_slot] = relid;
    2829                 :    21173617 :         FAST_PATH_SET_LOCKMODE(MyProc, unused_slot, lockmode);
    2830                 :    21173617 :         ++FastPathLocalUseCounts[group];
    2831                 :    21173617 :         return true;
    2832                 :             :     }
    2833                 :             : 
    2834                 :             :     /* No existing entry, and no empty slot. */
    2835                 :           0 :     return false;
    2836                 :             : }
    2837                 :             : 
    2838                 :             : /*
    2839                 :             :  * FastPathUnGrantRelationLock
    2840                 :             :  *      Release fast-path lock, if present.  Update backend-private local
    2841                 :             :  *      use count, while we're at it.
    2842                 :             :  */
    2843                 :             : static bool
    2844                 :    21947102 : FastPathUnGrantRelationLock(Oid relid, LOCKMODE lockmode)
    2845                 :             : {
    2846                 :             :     uint32      i;
    2847                 :    21947102 :     bool        result = false;
    2848                 :             : 
    2849                 :             :     /* fast-path group the lock belongs to */
    2850                 :    21947102 :     uint32      group = FAST_PATH_REL_GROUP(relid);
    2851                 :             : 
    2852                 :    21947102 :     FastPathLocalUseCounts[group] = 0;
    2853         [ +  + ]:   373100734 :     for (i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
    2854                 :             :     {
    2855                 :             :         /* index into the whole per-backend array */
    2856                 :   351153632 :         uint32      f = FAST_PATH_SLOT(group, i);
    2857                 :             : 
    2858         [ +  + ]:   351153632 :         if (MyProc->fpRelId[f] == relid
    2859         [ +  + ]:    32702847 :             && FAST_PATH_CHECK_LOCKMODE(MyProc, f, lockmode))
    2860                 :             :         {
    2861                 :             :             Assert(!result);
    2862                 :    21826593 :             FAST_PATH_CLEAR_LOCKMODE(MyProc, f, lockmode);
    2863                 :    21826593 :             result = true;
    2864                 :             :             /* we continue iterating so as to update FastPathLocalUseCount */
    2865                 :             :         }
    2866         [ +  + ]:   351153632 :         if (FAST_PATH_GET_BITS(MyProc, f) != 0)
    2867                 :     8893542 :             ++FastPathLocalUseCounts[group];
    2868                 :             :     }
    2869                 :    21947102 :     return result;
    2870                 :             : }
    2871                 :             : 
    2872                 :             : /*
    2873                 :             :  * FastPathTransferRelationLocks
    2874                 :             :  *      Transfer locks matching the given lock tag from per-backend fast-path
    2875                 :             :  *      arrays to the shared hash table.
    2876                 :             :  *
    2877                 :             :  * Returns true if successful, false if ran out of shared memory.
    2878                 :             :  */
    2879                 :             : static bool
    2880                 :      251906 : FastPathTransferRelationLocks(LockMethod lockMethodTable, const LOCKTAG *locktag,
    2881                 :             :                               uint32 hashcode)
    2882                 :             : {
    2883                 :      251906 :     LWLock     *partitionLock = LockHashPartitionLock(hashcode);
    2884                 :      251906 :     Oid         relid = locktag->locktag_field2;
    2885                 :             :     uint32      i;
    2886                 :             : 
    2887                 :             :     /* fast-path group the lock belongs to */
    2888                 :      251906 :     uint32      group = FAST_PATH_REL_GROUP(relid);
    2889                 :             : 
    2890                 :             :     /*
    2891                 :             :      * Every PGPROC that can potentially hold a fast-path lock is present in
    2892                 :             :      * ProcGlobal->allProcs.  Prepared transactions are not, but any
    2893                 :             :      * outstanding fast-path locks held by prepared transactions are
    2894                 :             :      * transferred to the main lock table.
    2895                 :             :      */
    2896         [ +  + ]:    37474903 :     for (i = 0; i < ProcGlobal->allProcCount; i++)
    2897                 :             :     {
    2898                 :    37222997 :         PGPROC     *proc = GetPGProcByNumber(i);
    2899                 :             :         uint32      j;
    2900                 :             : 
    2901                 :    37222997 :         LWLockAcquire(&proc->fpInfoLock, LW_EXCLUSIVE);
    2902                 :             : 
    2903                 :             :         /*
    2904                 :             :          * If the target backend isn't referencing the same database as the
    2905                 :             :          * lock, then we needn't examine the individual relation IDs at all;
    2906                 :             :          * none of them can be relevant.
    2907                 :             :          *
    2908                 :             :          * proc->databaseId is set at backend startup time and never changes
    2909                 :             :          * thereafter, so it might be safe to perform this test before
    2910                 :             :          * acquiring &proc->fpInfoLock.  In particular, it's certainly safe to
    2911                 :             :          * assume that if the target backend holds any fast-path locks, it
    2912                 :             :          * must have performed a memory-fencing operation (in particular, an
    2913                 :             :          * LWLock acquisition) since setting proc->databaseId.  However, it's
    2914                 :             :          * less clear that our backend is certain to have performed a memory
    2915                 :             :          * fencing operation since the other backend set proc->databaseId.  So
    2916                 :             :          * for now, we test it after acquiring the LWLock just to be safe.
    2917                 :             :          *
    2918                 :             :          * Also skip groups without any registered fast-path locks.
    2919                 :             :          */
    2920         [ +  + ]:    37222997 :         if (proc->databaseId != locktag->locktag_field1 ||
    2921         [ +  + ]:    14687443 :             proc->fpLockBits[group] == 0)
    2922                 :             :         {
    2923                 :    37077528 :             LWLockRelease(&proc->fpInfoLock);
    2924                 :    37077528 :             continue;
    2925                 :             :         }
    2926                 :             : 
    2927         [ +  + ]:     2471298 :         for (j = 0; j < FP_LOCK_SLOTS_PER_GROUP; j++)
    2928                 :             :         {
    2929                 :             :             uint32      lockmode;
    2930                 :             : 
    2931                 :             :             /* index into the whole per-backend array */
    2932                 :     2327387 :             uint32      f = FAST_PATH_SLOT(group, j);
    2933                 :             : 
    2934                 :             :             /* Look for an allocated slot matching the given relid. */
    2935   [ +  +  +  + ]:     2327387 :             if (relid != proc->fpRelId[f] || FAST_PATH_GET_BITS(proc, f) == 0)
    2936                 :     2325829 :                 continue;
    2937                 :             : 
    2938                 :             :             /* Find or create lock object. */
    2939                 :        1558 :             LWLockAcquire(partitionLock, LW_EXCLUSIVE);
    2940                 :        1558 :             for (lockmode = FAST_PATH_LOCKNUMBER_OFFSET;
    2941         [ +  + ]:        6232 :                  lockmode < FAST_PATH_LOCKNUMBER_OFFSET + FAST_PATH_BITS_PER_SLOT;
    2942                 :        4674 :                  ++lockmode)
    2943                 :             :             {
    2944                 :             :                 PROCLOCK   *proclock;
    2945                 :             : 
    2946         [ +  + ]:        4674 :                 if (!FAST_PATH_CHECK_LOCKMODE(proc, f, lockmode))
    2947                 :        3050 :                     continue;
    2948                 :        1624 :                 proclock = SetupLockInTable(lockMethodTable, proc, locktag,
    2949                 :             :                                             hashcode, lockmode);
    2950         [ -  + ]:        1624 :                 if (!proclock)
    2951                 :             :                 {
    2952                 :           0 :                     LWLockRelease(partitionLock);
    2953                 :           0 :                     LWLockRelease(&proc->fpInfoLock);
    2954                 :           0 :                     return false;
    2955                 :             :                 }
    2956                 :        1624 :                 GrantLock(proclock->tag.myLock, proclock, lockmode);
    2957                 :        1624 :                 FAST_PATH_CLEAR_LOCKMODE(proc, f, lockmode);
    2958                 :             :             }
    2959                 :        1558 :             LWLockRelease(partitionLock);
    2960                 :             : 
    2961                 :             :             /* No need to examine remaining slots. */
    2962                 :        1558 :             break;
    2963                 :             :         }
    2964                 :      145469 :         LWLockRelease(&proc->fpInfoLock);
    2965                 :             :     }
    2966                 :      251906 :     return true;
    2967                 :             : }
    2968                 :             : 
    2969                 :             : /*
    2970                 :             :  * FastPathGetRelationLockEntry
    2971                 :             :  *      Return the PROCLOCK for a lock originally taken via the fast-path,
    2972                 :             :  *      transferring it to the primary lock table if necessary.
    2973                 :             :  *
    2974                 :             :  * Note: caller takes care of updating the locallock object.
    2975                 :             :  */
    2976                 :             : static PROCLOCK *
    2977                 :         348 : FastPathGetRelationLockEntry(LOCALLOCK *locallock)
    2978                 :             : {
    2979                 :         348 :     LockMethod  lockMethodTable = LockMethods[DEFAULT_LOCKMETHOD];
    2980                 :         348 :     LOCKTAG    *locktag = &locallock->tag.lock;
    2981                 :         348 :     PROCLOCK   *proclock = NULL;
    2982                 :         348 :     LWLock     *partitionLock = LockHashPartitionLock(locallock->hashcode);
    2983                 :         348 :     Oid         relid = locktag->locktag_field2;
    2984                 :             :     uint32      i,
    2985                 :             :                 group;
    2986                 :             : 
    2987                 :             :     /* fast-path group the lock belongs to */
    2988                 :         348 :     group = FAST_PATH_REL_GROUP(relid);
    2989                 :             : 
    2990                 :         348 :     LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
    2991                 :             : 
    2992         [ +  + ]:        5578 :     for (i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
    2993                 :             :     {
    2994                 :             :         uint32      lockmode;
    2995                 :             : 
    2996                 :             :         /* index into the whole per-backend array */
    2997                 :        5562 :         uint32      f = FAST_PATH_SLOT(group, i);
    2998                 :             : 
    2999                 :             :         /* Look for an allocated slot matching the given relid. */
    3000   [ +  +  -  + ]:        5562 :         if (relid != MyProc->fpRelId[f] || FAST_PATH_GET_BITS(MyProc, f) == 0)
    3001                 :        5230 :             continue;
    3002                 :             : 
    3003                 :             :         /* If we don't have a lock of the given mode, forget it! */
    3004                 :         332 :         lockmode = locallock->tag.mode;
    3005         [ -  + ]:         332 :         if (!FAST_PATH_CHECK_LOCKMODE(MyProc, f, lockmode))
    3006                 :           0 :             break;
    3007                 :             : 
    3008                 :             :         /* Find or create lock object. */
    3009                 :         332 :         LWLockAcquire(partitionLock, LW_EXCLUSIVE);
    3010                 :             : 
    3011                 :         332 :         proclock = SetupLockInTable(lockMethodTable, MyProc, locktag,
    3012                 :             :                                     locallock->hashcode, lockmode);
    3013         [ -  + ]:         332 :         if (!proclock)
    3014                 :             :         {
    3015                 :           0 :             LWLockRelease(partitionLock);
    3016                 :           0 :             LWLockRelease(&MyProc->fpInfoLock);
    3017         [ #  # ]:           0 :             ereport(ERROR,
    3018                 :             :                     (errcode(ERRCODE_OUT_OF_MEMORY),
    3019                 :             :                      errmsg("out of shared memory"),
    3020                 :             :                      errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
    3021                 :             :         }
    3022                 :         332 :         GrantLock(proclock->tag.myLock, proclock, lockmode);
    3023                 :         332 :         FAST_PATH_CLEAR_LOCKMODE(MyProc, f, lockmode);
    3024                 :             : 
    3025                 :         332 :         LWLockRelease(partitionLock);
    3026                 :             : 
    3027                 :             :         /* No need to examine remaining slots. */
    3028                 :         332 :         break;
    3029                 :             :     }
    3030                 :             : 
    3031                 :         348 :     LWLockRelease(&MyProc->fpInfoLock);
    3032                 :             : 
    3033                 :             :     /* Lock may have already been transferred by some other backend. */
    3034         [ +  + ]:         348 :     if (proclock == NULL)
    3035                 :             :     {
    3036                 :             :         LOCK       *lock;
    3037                 :             :         PROCLOCKTAG proclocktag;
    3038                 :             :         uint32      proclock_hashcode;
    3039                 :             : 
    3040                 :          16 :         LWLockAcquire(partitionLock, LW_SHARED);
    3041                 :             : 
    3042                 :          16 :         lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
    3043                 :             :                                                     locktag,
    3044                 :             :                                                     locallock->hashcode,
    3045                 :             :                                                     HASH_FIND,
    3046                 :             :                                                     NULL);
    3047         [ -  + ]:          16 :         if (!lock)
    3048         [ #  # ]:           0 :             elog(ERROR, "failed to re-find shared lock object");
    3049                 :             : 
    3050                 :          16 :         proclocktag.myLock = lock;
    3051                 :          16 :         proclocktag.myProc = MyProc;
    3052                 :             : 
    3053                 :          16 :         proclock_hashcode = ProcLockHashCode(&proclocktag, locallock->hashcode);
    3054                 :             :         proclock = (PROCLOCK *)
    3055                 :          16 :             hash_search_with_hash_value(LockMethodProcLockHash,
    3056                 :             :                                         &proclocktag,
    3057                 :             :                                         proclock_hashcode,
    3058                 :             :                                         HASH_FIND,
    3059                 :             :                                         NULL);
    3060         [ -  + ]:          16 :         if (!proclock)
    3061         [ #  # ]:           0 :             elog(ERROR, "failed to re-find shared proclock object");
    3062                 :          16 :         LWLockRelease(partitionLock);
    3063                 :             :     }
    3064                 :             : 
    3065                 :         348 :     return proclock;
    3066                 :             : }
    3067                 :             : 
    3068                 :             : /*
    3069                 :             :  * GetLockConflicts
    3070                 :             :  *      Get an array of VirtualTransactionIds of xacts currently holding locks
    3071                 :             :  *      that would conflict with the specified lock/lockmode.
    3072                 :             :  *      xacts merely awaiting such a lock are NOT reported.
    3073                 :             :  *
    3074                 :             :  * The result array is palloc'd and is terminated with an invalid VXID.
    3075                 :             :  * *countp, if not null, is updated to the number of items set.
    3076                 :             :  *
    3077                 :             :  * Of course, the result could be out of date by the time it's returned, so
    3078                 :             :  * use of this function has to be thought about carefully.  Similarly, a
    3079                 :             :  * PGPROC with no "lxid" will be considered non-conflicting regardless of any
    3080                 :             :  * lock it holds.  Existing callers don't care about a locker after that
    3081                 :             :  * locker's pg_xact updates complete.  CommitTransaction() clears "lxid" after
    3082                 :             :  * pg_xact updates and before releasing locks.
    3083                 :             :  *
    3084                 :             :  * Note we never include the current xact's vxid in the result array,
    3085                 :             :  * since an xact never blocks itself.
    3086                 :             :  */
    3087                 :             : VirtualTransactionId *
    3088                 :        1838 : GetLockConflicts(const LOCKTAG *locktag, LOCKMODE lockmode, int *countp)
    3089                 :             : {
    3090                 :             :     static VirtualTransactionId *vxids;
    3091                 :        1838 :     LOCKMETHODID lockmethodid = locktag->locktag_lockmethodid;
    3092                 :             :     LockMethod  lockMethodTable;
    3093                 :             :     LOCK       *lock;
    3094                 :             :     LOCKMASK    conflictMask;
    3095                 :             :     dlist_iter  proclock_iter;
    3096                 :             :     PROCLOCK   *proclock;
    3097                 :             :     uint32      hashcode;
    3098                 :             :     LWLock     *partitionLock;
    3099                 :        1838 :     int         count = 0;
    3100                 :        1838 :     int         fast_count = 0;
    3101                 :             : 
    3102   [ +  -  -  + ]:        1838 :     if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
    3103         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock method: %d", lockmethodid);
    3104                 :        1838 :     lockMethodTable = LockMethods[lockmethodid];
    3105   [ +  -  -  + ]:        1838 :     if (lockmode <= 0 || lockmode > lockMethodTable->numLockModes)
    3106         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock mode: %d", lockmode);
    3107                 :             : 
    3108                 :             :     /*
    3109                 :             :      * Allocate memory to store results, and fill with InvalidVXID.  We only
    3110                 :             :      * need enough space for MaxBackends + max_prepared_xacts + a terminator.
    3111                 :             :      * InHotStandby allocate once in TopMemoryContext.
    3112                 :             :      */
    3113         [ +  + ]:        1838 :     if (InHotStandby)
    3114                 :             :     {
    3115         [ +  + ]:           4 :         if (vxids == NULL)
    3116                 :           1 :             vxids = (VirtualTransactionId *)
    3117                 :           1 :                 MemoryContextAlloc(TopMemoryContext,
    3118                 :             :                                    sizeof(VirtualTransactionId) *
    3119                 :           1 :                                    (MaxBackends + max_prepared_xacts + 1));
    3120                 :             :     }
    3121                 :             :     else
    3122                 :        1834 :         vxids = palloc0_array(VirtualTransactionId, (MaxBackends + max_prepared_xacts + 1));
    3123                 :             : 
    3124                 :             :     /* Compute hash code and partition lock, and look up conflicting modes. */
    3125                 :        1838 :     hashcode = LockTagHashCode(locktag);
    3126                 :        1838 :     partitionLock = LockHashPartitionLock(hashcode);
    3127                 :        1838 :     conflictMask = lockMethodTable->conflictTab[lockmode];
    3128                 :             : 
    3129                 :             :     /*
    3130                 :             :      * Fast path locks might not have been entered in the primary lock table.
    3131                 :             :      * If the lock we're dealing with could conflict with such a lock, we must
    3132                 :             :      * examine each backend's fast-path array for conflicts.
    3133                 :             :      */
    3134   [ +  -  +  -  :        1838 :     if (ConflictsWithRelationFastPath(locktag, lockmode))
             +  -  +  - ]
    3135                 :             :     {
    3136                 :        1838 :         Oid         relid = locktag->locktag_field2;
    3137                 :             :         VirtualTransactionId vxid;
    3138                 :             : 
    3139                 :             :         /* fast-path group the lock belongs to */
    3140                 :        1838 :         uint32      group = FAST_PATH_REL_GROUP(relid);
    3141                 :             : 
    3142                 :             :         /*
    3143                 :             :          * Iterate over relevant PGPROCs.  Anything held by a prepared
    3144                 :             :          * transaction will have been transferred to the primary lock table,
    3145                 :             :          * so we need not worry about those.  This is all a bit fuzzy, because
    3146                 :             :          * new locks could be taken after we've visited a particular
    3147                 :             :          * partition, but the callers had better be prepared to deal with that
    3148                 :             :          * anyway, since the locks could equally well be taken between the
    3149                 :             :          * time we return the value and the time the caller does something
    3150                 :             :          * with it.
    3151                 :             :          */
    3152         [ +  + ]:      291062 :         for (uint32 i = 0; i < ProcGlobal->allProcCount; i++)
    3153                 :             :         {
    3154                 :      289224 :             PGPROC     *proc = GetPGProcByNumber(i);
    3155                 :             :             uint32      j;
    3156                 :             : 
    3157                 :             :             /* A backend never blocks itself */
    3158         [ +  + ]:      289224 :             if (proc == MyProc)
    3159                 :        1838 :                 continue;
    3160                 :             : 
    3161                 :      287386 :             LWLockAcquire(&proc->fpInfoLock, LW_SHARED);
    3162                 :             : 
    3163                 :             :             /*
    3164                 :             :              * If the target backend isn't referencing the same database as
    3165                 :             :              * the lock, then we needn't examine the individual relation IDs
    3166                 :             :              * at all; none of them can be relevant.
    3167                 :             :              *
    3168                 :             :              * See FastPathTransferRelationLocks() for discussion of why we do
    3169                 :             :              * this test after acquiring the lock.
    3170                 :             :              *
    3171                 :             :              * Also skip groups without any registered fast-path locks.
    3172                 :             :              */
    3173         [ +  + ]:      287386 :             if (proc->databaseId != locktag->locktag_field1 ||
    3174         [ +  + ]:      116740 :                 proc->fpLockBits[group] == 0)
    3175                 :             :             {
    3176                 :      286980 :                 LWLockRelease(&proc->fpInfoLock);
    3177                 :      286980 :                 continue;
    3178                 :             :             }
    3179                 :             : 
    3180         [ +  + ]:        6684 :             for (j = 0; j < FP_LOCK_SLOTS_PER_GROUP; j++)
    3181                 :             :             {
    3182                 :             :                 uint32      lockmask;
    3183                 :             : 
    3184                 :             :                 /* index into the whole per-backend array */
    3185                 :        6496 :                 uint32      f = FAST_PATH_SLOT(group, j);
    3186                 :             : 
    3187                 :             :                 /* Look for an allocated slot matching the given relid. */
    3188         [ +  + ]:        6496 :                 if (relid != proc->fpRelId[f])
    3189                 :        6278 :                     continue;
    3190                 :         218 :                 lockmask = FAST_PATH_GET_BITS(proc, f);
    3191         [ -  + ]:         218 :                 if (!lockmask)
    3192                 :           0 :                     continue;
    3193                 :         218 :                 lockmask <<= FAST_PATH_LOCKNUMBER_OFFSET;
    3194                 :             : 
    3195                 :             :                 /*
    3196                 :             :                  * There can only be one entry per relation, so if we found it
    3197                 :             :                  * and it doesn't conflict, we can skip the rest of the slots.
    3198                 :             :                  */
    3199         [ +  + ]:         218 :                 if ((lockmask & conflictMask) == 0)
    3200                 :           5 :                     break;
    3201                 :             : 
    3202                 :             :                 /* Conflict! */
    3203                 :         213 :                 GET_VXID_FROM_PGPROC(vxid, *proc);
    3204                 :             : 
    3205         [ +  - ]:         213 :                 if (VirtualTransactionIdIsValid(vxid))
    3206                 :         213 :                     vxids[count++] = vxid;
    3207                 :             :                 /* else, xact already committed or aborted */
    3208                 :             : 
    3209                 :             :                 /* No need to examine remaining slots. */
    3210                 :         213 :                 break;
    3211                 :             :             }
    3212                 :             : 
    3213                 :         406 :             LWLockRelease(&proc->fpInfoLock);
    3214                 :             :         }
    3215                 :             :     }
    3216                 :             : 
    3217                 :             :     /* Remember how many fast-path conflicts we found. */
    3218                 :        1838 :     fast_count = count;
    3219                 :             : 
    3220                 :             :     /*
    3221                 :             :      * Look up the lock object matching the tag.
    3222                 :             :      */
    3223                 :        1838 :     LWLockAcquire(partitionLock, LW_SHARED);
    3224                 :             : 
    3225                 :        1838 :     lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
    3226                 :             :                                                 locktag,
    3227                 :             :                                                 hashcode,
    3228                 :             :                                                 HASH_FIND,
    3229                 :             :                                                 NULL);
    3230         [ +  + ]:        1838 :     if (!lock)
    3231                 :             :     {
    3232                 :             :         /*
    3233                 :             :          * If the lock object doesn't exist, there is nothing holding a lock
    3234                 :             :          * on this lockable object.
    3235                 :             :          */
    3236                 :          72 :         LWLockRelease(partitionLock);
    3237                 :          72 :         vxids[count].procNumber = INVALID_PROC_NUMBER;
    3238                 :          72 :         vxids[count].localTransactionId = InvalidLocalTransactionId;
    3239         [ -  + ]:          72 :         if (countp)
    3240                 :           0 :             *countp = count;
    3241                 :          72 :         return vxids;
    3242                 :             :     }
    3243                 :             : 
    3244                 :             :     /*
    3245                 :             :      * Examine each existing holder (or awaiter) of the lock.
    3246                 :             :      */
    3247   [ +  -  +  + ]:        3547 :     dlist_foreach(proclock_iter, &lock->procLocks)
    3248                 :             :     {
    3249                 :        1781 :         proclock = dlist_container(PROCLOCK, lockLink, proclock_iter.cur);
    3250                 :             : 
    3251         [ +  + ]:        1781 :         if (conflictMask & proclock->holdMask)
    3252                 :             :         {
    3253                 :        1777 :             PGPROC     *proc = proclock->tag.myProc;
    3254                 :             : 
    3255                 :             :             /* A backend never blocks itself */
    3256         [ +  + ]:        1777 :             if (proc != MyProc)
    3257                 :             :             {
    3258                 :             :                 VirtualTransactionId vxid;
    3259                 :             : 
    3260                 :          15 :                 GET_VXID_FROM_PGPROC(vxid, *proc);
    3261                 :             : 
    3262         [ +  - ]:          15 :                 if (VirtualTransactionIdIsValid(vxid))
    3263                 :             :                 {
    3264                 :             :                     int         i;
    3265                 :             : 
    3266                 :             :                     /* Avoid duplicate entries. */
    3267         [ +  + ]:          25 :                     for (i = 0; i < fast_count; ++i)
    3268   [ -  +  -  - ]:          10 :                         if (VirtualTransactionIdEquals(vxids[i], vxid))
    3269                 :           0 :                             break;
    3270         [ +  - ]:          15 :                     if (i >= fast_count)
    3271                 :          15 :                         vxids[count++] = vxid;
    3272                 :             :                 }
    3273                 :             :                 /* else, xact already committed or aborted */
    3274                 :             :             }
    3275                 :             :         }
    3276                 :             :     }
    3277                 :             : 
    3278                 :        1766 :     LWLockRelease(partitionLock);
    3279                 :             : 
    3280         [ -  + ]:        1766 :     if (count > MaxBackends + max_prepared_xacts)    /* should never happen */
    3281         [ #  # ]:           0 :         elog(PANIC, "too many conflicting locks found");
    3282                 :             : 
    3283                 :        1766 :     vxids[count].procNumber = INVALID_PROC_NUMBER;
    3284                 :        1766 :     vxids[count].localTransactionId = InvalidLocalTransactionId;
    3285         [ +  + ]:        1766 :     if (countp)
    3286                 :        1763 :         *countp = count;
    3287                 :        1766 :     return vxids;
    3288                 :             : }
    3289                 :             : 
    3290                 :             : /*
    3291                 :             :  * Find a lock in the shared lock table and release it.  It is the caller's
    3292                 :             :  * responsibility to verify that this is a sane thing to do.  (For example, it
    3293                 :             :  * would be bad to release a lock here if there might still be a LOCALLOCK
    3294                 :             :  * object with pointers to it.)
    3295                 :             :  *
    3296                 :             :  * We currently use this in two situations: first, to release locks held by
    3297                 :             :  * prepared transactions on commit (see lock_twophase_postcommit); and second,
    3298                 :             :  * to release locks taken via the fast-path, transferred to the main hash
    3299                 :             :  * table, and then released (see LockReleaseAll).
    3300                 :             :  */
    3301                 :             : static void
    3302                 :        2808 : LockRefindAndRelease(LockMethod lockMethodTable, PGPROC *proc,
    3303                 :             :                      LOCKTAG *locktag, LOCKMODE lockmode,
    3304                 :             :                      bool decrement_strong_lock_count)
    3305                 :             : {
    3306                 :             :     LOCK       *lock;
    3307                 :             :     PROCLOCK   *proclock;
    3308                 :             :     PROCLOCKTAG proclocktag;
    3309                 :             :     uint32      hashcode;
    3310                 :             :     uint32      proclock_hashcode;
    3311                 :             :     LWLock     *partitionLock;
    3312                 :             :     bool        wakeupNeeded;
    3313                 :             : 
    3314                 :        2808 :     hashcode = LockTagHashCode(locktag);
    3315                 :        2808 :     partitionLock = LockHashPartitionLock(hashcode);
    3316                 :             : 
    3317                 :        2808 :     LWLockAcquire(partitionLock, LW_EXCLUSIVE);
    3318                 :             : 
    3319                 :             :     /*
    3320                 :             :      * Re-find the lock object (it had better be there).
    3321                 :             :      */
    3322                 :        2808 :     lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
    3323                 :             :                                                 locktag,
    3324                 :             :                                                 hashcode,
    3325                 :             :                                                 HASH_FIND,
    3326                 :             :                                                 NULL);
    3327         [ -  + ]:        2808 :     if (!lock)
    3328         [ #  # ]:           0 :         elog(PANIC, "failed to re-find shared lock object");
    3329                 :             : 
    3330                 :             :     /*
    3331                 :             :      * Re-find the proclock object (ditto).
    3332                 :             :      */
    3333                 :        2808 :     proclocktag.myLock = lock;
    3334                 :        2808 :     proclocktag.myProc = proc;
    3335                 :             : 
    3336                 :        2808 :     proclock_hashcode = ProcLockHashCode(&proclocktag, hashcode);
    3337                 :             : 
    3338                 :        2808 :     proclock = (PROCLOCK *) hash_search_with_hash_value(LockMethodProcLockHash,
    3339                 :             :                                                         &proclocktag,
    3340                 :             :                                                         proclock_hashcode,
    3341                 :             :                                                         HASH_FIND,
    3342                 :             :                                                         NULL);
    3343         [ -  + ]:        2808 :     if (!proclock)
    3344         [ #  # ]:           0 :         elog(PANIC, "failed to re-find shared proclock object");
    3345                 :             : 
    3346                 :             :     /*
    3347                 :             :      * Double-check that we are actually holding a lock of the type we want to
    3348                 :             :      * release.
    3349                 :             :      */
    3350         [ -  + ]:        2808 :     if (!(proclock->holdMask & LOCKBIT_ON(lockmode)))
    3351                 :             :     {
    3352                 :             :         PROCLOCK_PRINT("lock_twophase_postcommit: WRONGTYPE", proclock);
    3353                 :           0 :         LWLockRelease(partitionLock);
    3354         [ #  # ]:           0 :         elog(WARNING, "you don't own a lock of type %s",
    3355                 :             :              lockMethodTable->lockModeNames[lockmode]);
    3356                 :           0 :         return;
    3357                 :             :     }
    3358                 :             : 
    3359                 :             :     /*
    3360                 :             :      * Do the releasing.  CleanUpLock will waken any now-wakable waiters.
    3361                 :             :      */
    3362                 :        2808 :     wakeupNeeded = UnGrantLock(lock, lockmode, proclock, lockMethodTable);
    3363                 :             : 
    3364                 :        2808 :     CleanUpLock(lock, proclock,
    3365                 :             :                 lockMethodTable, hashcode,
    3366                 :             :                 wakeupNeeded);
    3367                 :             : 
    3368                 :        2808 :     LWLockRelease(partitionLock);
    3369                 :             : 
    3370                 :             :     /*
    3371                 :             :      * Decrement strong lock count.  This logic is needed only for 2PC.
    3372                 :             :      */
    3373         [ +  + ]:        2808 :     if (decrement_strong_lock_count
    3374   [ +  -  +  +  :         917 :         && ConflictsWithRelationFastPath(locktag, lockmode))
             +  +  +  + ]
    3375                 :             :     {
    3376                 :         116 :         uint32      fasthashcode = FastPathStrongLockHashPartition(hashcode);
    3377                 :             : 
    3378                 :         116 :         SpinLockAcquire(&FastPathStrongRelationLocks->mutex);
    3379                 :             :         Assert(FastPathStrongRelationLocks->count[fasthashcode] > 0);
    3380                 :         116 :         FastPathStrongRelationLocks->count[fasthashcode]--;
    3381                 :         116 :         SpinLockRelease(&FastPathStrongRelationLocks->mutex);
    3382                 :             :     }
    3383                 :             : }
    3384                 :             : 
    3385                 :             : /*
    3386                 :             :  * CheckForSessionAndXactLocks
    3387                 :             :  *      Check to see if transaction holds both session-level and xact-level
    3388                 :             :  *      locks on the same object; if so, throw an error.
    3389                 :             :  *
    3390                 :             :  * If we have both session- and transaction-level locks on the same object,
    3391                 :             :  * PREPARE TRANSACTION must fail.  This should never happen with regular
    3392                 :             :  * locks, since we only take those at session level in some special operations
    3393                 :             :  * like VACUUM.  It's possible to hit this with advisory locks, though.
    3394                 :             :  *
    3395                 :             :  * It would be nice if we could keep the session hold and give away the
    3396                 :             :  * transactional hold to the prepared xact.  However, that would require two
    3397                 :             :  * PROCLOCK objects, and we cannot be sure that another PROCLOCK will be
    3398                 :             :  * available when it comes time for PostPrepare_Locks to do the deed.
    3399                 :             :  * So for now, we error out while we can still do so safely.
    3400                 :             :  *
    3401                 :             :  * Since the LOCALLOCK table stores a separate entry for each lockmode,
    3402                 :             :  * we can't implement this check by examining LOCALLOCK entries in isolation.
    3403                 :             :  * We must build a transient hashtable that is indexed by locktag only.
    3404                 :             :  */
    3405                 :             : static void
    3406                 :         326 : CheckForSessionAndXactLocks(void)
    3407                 :             : {
    3408                 :             :     typedef struct
    3409                 :             :     {
    3410                 :             :         LOCKTAG     lock;       /* identifies the lockable object */
    3411                 :             :         bool        sessLock;   /* is any lockmode held at session level? */
    3412                 :             :         bool        xactLock;   /* is any lockmode held at xact level? */
    3413                 :             :     } PerLockTagEntry;
    3414                 :             : 
    3415                 :             :     HASHCTL     hash_ctl;
    3416                 :             :     HTAB       *lockhtab;
    3417                 :             :     HASH_SEQ_STATUS status;
    3418                 :             :     LOCALLOCK  *locallock;
    3419                 :             : 
    3420                 :             :     /* Create a local hash table keyed by LOCKTAG only */
    3421                 :         326 :     hash_ctl.keysize = sizeof(LOCKTAG);
    3422                 :         326 :     hash_ctl.entrysize = sizeof(PerLockTagEntry);
    3423                 :         326 :     hash_ctl.hcxt = CurrentMemoryContext;
    3424                 :             : 
    3425                 :         326 :     lockhtab = hash_create("CheckForSessionAndXactLocks table",
    3426                 :             :                            256, /* arbitrary initial size */
    3427                 :             :                            &hash_ctl,
    3428                 :             :                            HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    3429                 :             : 
    3430                 :             :     /* Scan local lock table to find entries for each LOCKTAG */
    3431                 :         326 :     hash_seq_init(&status, LockMethodLocalHash);
    3432                 :             : 
    3433         [ +  + ]:        1245 :     while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
    3434                 :             :     {
    3435                 :         921 :         LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
    3436                 :             :         PerLockTagEntry *hentry;
    3437                 :             :         bool        found;
    3438                 :             :         int         i;
    3439                 :             : 
    3440                 :             :         /*
    3441                 :             :          * Ignore VXID locks.  We don't want those to be held by prepared
    3442                 :             :          * transactions, since they aren't meaningful after a restart.
    3443                 :             :          */
    3444         [ -  + ]:         921 :         if (locallock->tag.lock.locktag_type == LOCKTAG_VIRTUALTRANSACTION)
    3445                 :           0 :             continue;
    3446                 :             : 
    3447                 :             :         /* Ignore it if we don't actually hold the lock */
    3448         [ -  + ]:         921 :         if (locallock->nLocks <= 0)
    3449                 :           0 :             continue;
    3450                 :             : 
    3451                 :             :         /* Otherwise, find or make an entry in lockhtab */
    3452                 :         921 :         hentry = (PerLockTagEntry *) hash_search(lockhtab,
    3453                 :         921 :                                                  &locallock->tag.lock,
    3454                 :             :                                                  HASH_ENTER, &found);
    3455         [ +  + ]:         921 :         if (!found)             /* initialize, if newly created */
    3456                 :         828 :             hentry->sessLock = hentry->xactLock = false;
    3457                 :             : 
    3458                 :             :         /* Scan to see if we hold lock at session or xact level or both */
    3459         [ +  + ]:        1842 :         for (i = locallock->numLockOwners - 1; i >= 0; i--)
    3460                 :             :         {
    3461         [ +  + ]:         921 :             if (lockOwners[i].owner == NULL)
    3462                 :          10 :                 hentry->sessLock = true;
    3463                 :             :             else
    3464                 :         911 :                 hentry->xactLock = true;
    3465                 :             :         }
    3466                 :             : 
    3467                 :             :         /*
    3468                 :             :          * We can throw error immediately when we see both types of locks; no
    3469                 :             :          * need to wait around to see if there are more violations.
    3470                 :             :          */
    3471   [ +  +  +  + ]:         921 :         if (hentry->sessLock && hentry->xactLock)
    3472         [ +  - ]:           2 :             ereport(ERROR,
    3473                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3474                 :             :                      errmsg("cannot PREPARE while holding both session-level and transaction-level locks on the same object")));
    3475                 :             :     }
    3476                 :             : 
    3477                 :             :     /* Success, so clean up */
    3478                 :         324 :     hash_destroy(lockhtab);
    3479                 :         324 : }
    3480                 :             : 
    3481                 :             : /*
    3482                 :             :  * AtPrepare_Locks
    3483                 :             :  *      Do the preparatory work for a PREPARE: make 2PC state file records
    3484                 :             :  *      for all locks currently held.
    3485                 :             :  *
    3486                 :             :  * Session-level locks are ignored, as are VXID locks.
    3487                 :             :  *
    3488                 :             :  * For the most part, we don't need to touch shared memory for this ---
    3489                 :             :  * all the necessary state information is in the locallock table.
    3490                 :             :  * Fast-path locks are an exception, however: we move any such locks to
    3491                 :             :  * the main table before allowing PREPARE TRANSACTION to succeed.
    3492                 :             :  */
    3493                 :             : void
    3494                 :         326 : AtPrepare_Locks(void)
    3495                 :             : {
    3496                 :             :     HASH_SEQ_STATUS status;
    3497                 :             :     LOCALLOCK  *locallock;
    3498                 :             : 
    3499                 :             :     /* First, verify there aren't locks of both xact and session level */
    3500                 :         326 :     CheckForSessionAndXactLocks();
    3501                 :             : 
    3502                 :             :     /* Now do the per-locallock cleanup work */
    3503                 :         324 :     hash_seq_init(&status, LockMethodLocalHash);
    3504                 :             : 
    3505         [ +  + ]:        1239 :     while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
    3506                 :             :     {
    3507                 :             :         TwoPhaseLockRecord record;
    3508                 :         915 :         LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
    3509                 :             :         bool        haveSessionLock;
    3510                 :             :         bool        haveXactLock;
    3511                 :             :         int         i;
    3512                 :             : 
    3513                 :             :         /*
    3514                 :             :          * Ignore VXID locks.  We don't want those to be held by prepared
    3515                 :             :          * transactions, since they aren't meaningful after a restart.
    3516                 :             :          */
    3517         [ -  + ]:         915 :         if (locallock->tag.lock.locktag_type == LOCKTAG_VIRTUALTRANSACTION)
    3518                 :           8 :             continue;
    3519                 :             : 
    3520                 :             :         /* Ignore it if we don't actually hold the lock */
    3521         [ -  + ]:         915 :         if (locallock->nLocks <= 0)
    3522                 :           0 :             continue;
    3523                 :             : 
    3524                 :             :         /* Scan to see whether we hold it at session or transaction level */
    3525                 :         915 :         haveSessionLock = haveXactLock = false;
    3526         [ +  + ]:        1830 :         for (i = locallock->numLockOwners - 1; i >= 0; i--)
    3527                 :             :         {
    3528         [ +  + ]:         915 :             if (lockOwners[i].owner == NULL)
    3529                 :           8 :                 haveSessionLock = true;
    3530                 :             :             else
    3531                 :         907 :                 haveXactLock = true;
    3532                 :             :         }
    3533                 :             : 
    3534                 :             :         /* Ignore it if we have only session lock */
    3535         [ +  + ]:         915 :         if (!haveXactLock)
    3536                 :           8 :             continue;
    3537                 :             : 
    3538                 :             :         /* This can't happen, because we already checked it */
    3539         [ -  + ]:         907 :         if (haveSessionLock)
    3540         [ #  # ]:           0 :             ereport(ERROR,
    3541                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3542                 :             :                      errmsg("cannot PREPARE while holding both session-level and transaction-level locks on the same object")));
    3543                 :             : 
    3544                 :             :         /*
    3545                 :             :          * If the local lock was taken via the fast-path, we need to move it
    3546                 :             :          * to the primary lock table, or just get a pointer to the existing
    3547                 :             :          * primary lock table entry if by chance it's already been
    3548                 :             :          * transferred.
    3549                 :             :          */
    3550         [ +  + ]:         907 :         if (locallock->proclock == NULL)
    3551                 :             :         {
    3552                 :         348 :             locallock->proclock = FastPathGetRelationLockEntry(locallock);
    3553                 :         348 :             locallock->lock = locallock->proclock->tag.myLock;
    3554                 :             :         }
    3555                 :             : 
    3556                 :             :         /*
    3557                 :             :          * Arrange to not release any strong lock count held by this lock
    3558                 :             :          * entry.  We must retain the count until the prepared transaction is
    3559                 :             :          * committed or rolled back.
    3560                 :             :          */
    3561                 :         907 :         locallock->holdsStrongLockCount = false;
    3562                 :             : 
    3563                 :             :         /*
    3564                 :             :          * Create a 2PC record.
    3565                 :             :          */
    3566                 :         907 :         memcpy(&(record.locktag), &(locallock->tag.lock), sizeof(LOCKTAG));
    3567                 :         907 :         record.lockmode = locallock->tag.mode;
    3568                 :             : 
    3569                 :         907 :         RegisterTwoPhaseRecord(TWOPHASE_RM_LOCK_ID, 0,
    3570                 :             :                                &record, sizeof(TwoPhaseLockRecord));
    3571                 :             :     }
    3572                 :         324 : }
    3573                 :             : 
    3574                 :             : /*
    3575                 :             :  * PostPrepare_Locks
    3576                 :             :  *      Clean up after successful PREPARE
    3577                 :             :  *
    3578                 :             :  * Here, we want to transfer ownership of our locks to a dummy PGPROC
    3579                 :             :  * that's now associated with the prepared transaction, and we want to
    3580                 :             :  * clean out the corresponding entries in the LOCALLOCK table.
    3581                 :             :  *
    3582                 :             :  * Note: by removing the LOCALLOCK entries, we are leaving dangling
    3583                 :             :  * pointers in the transaction's resource owner.  This is OK at the
    3584                 :             :  * moment since resowner.c doesn't try to free locks retail at a toplevel
    3585                 :             :  * transaction commit or abort.  We could alternatively zero out nLocks
    3586                 :             :  * and leave the LOCALLOCK entries to be garbage-collected by LockReleaseAll,
    3587                 :             :  * but that probably costs more cycles.
    3588                 :             :  */
    3589                 :             : void
    3590                 :         324 : PostPrepare_Locks(FullTransactionId fxid)
    3591                 :             : {
    3592                 :         324 :     PGPROC     *newproc = TwoPhaseGetDummyProc(fxid, false);
    3593                 :             :     HASH_SEQ_STATUS status;
    3594                 :             :     LOCALLOCK  *locallock;
    3595                 :             :     LOCK       *lock;
    3596                 :             :     PROCLOCK   *proclock;
    3597                 :             :     PROCLOCKTAG proclocktag;
    3598                 :             :     int         partition;
    3599                 :             : 
    3600                 :             :     /* Can't prepare a lock group follower. */
    3601                 :             :     Assert(MyProc->lockGroupLeader == NULL ||
    3602                 :             :            MyProc->lockGroupLeader == MyProc);
    3603                 :             : 
    3604                 :             :     /* This is a critical section: any error means big trouble */
    3605                 :         324 :     START_CRIT_SECTION();
    3606                 :             : 
    3607                 :             :     /*
    3608                 :             :      * First we run through the locallock table and get rid of unwanted
    3609                 :             :      * entries, then we scan the process's proclocks and transfer them to the
    3610                 :             :      * target proc.
    3611                 :             :      *
    3612                 :             :      * We do this separately because we may have multiple locallock entries
    3613                 :             :      * pointing to the same proclock, and we daren't end up with any dangling
    3614                 :             :      * pointers.
    3615                 :             :      */
    3616                 :         324 :     hash_seq_init(&status, LockMethodLocalHash);
    3617                 :             : 
    3618         [ +  + ]:        1239 :     while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
    3619                 :             :     {
    3620                 :         915 :         LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
    3621                 :             :         bool        haveSessionLock;
    3622                 :             :         bool        haveXactLock;
    3623                 :             :         int         i;
    3624                 :             : 
    3625   [ +  -  -  + ]:         915 :         if (locallock->proclock == NULL || locallock->lock == NULL)
    3626                 :             :         {
    3627                 :             :             /*
    3628                 :             :              * We must've run out of shared memory while trying to set up this
    3629                 :             :              * lock.  Just forget the local entry.
    3630                 :             :              */
    3631                 :             :             Assert(locallock->nLocks == 0);
    3632                 :           0 :             RemoveLocalLock(locallock);
    3633                 :           0 :             continue;
    3634                 :             :         }
    3635                 :             : 
    3636                 :             :         /* Ignore VXID locks */
    3637         [ -  + ]:         915 :         if (locallock->tag.lock.locktag_type == LOCKTAG_VIRTUALTRANSACTION)
    3638                 :           0 :             continue;
    3639                 :             : 
    3640                 :             :         /* Scan to see whether we hold it at session or transaction level */
    3641                 :         915 :         haveSessionLock = haveXactLock = false;
    3642         [ +  + ]:        1830 :         for (i = locallock->numLockOwners - 1; i >= 0; i--)
    3643                 :             :         {
    3644         [ +  + ]:         915 :             if (lockOwners[i].owner == NULL)
    3645                 :           8 :                 haveSessionLock = true;
    3646                 :             :             else
    3647                 :         907 :                 haveXactLock = true;
    3648                 :             :         }
    3649                 :             : 
    3650                 :             :         /* Ignore it if we have only session lock */
    3651         [ +  + ]:         915 :         if (!haveXactLock)
    3652                 :           8 :             continue;
    3653                 :             : 
    3654                 :             :         /* This can't happen, because we already checked it */
    3655         [ -  + ]:         907 :         if (haveSessionLock)
    3656         [ #  # ]:           0 :             ereport(PANIC,
    3657                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3658                 :             :                      errmsg("cannot PREPARE while holding both session-level and transaction-level locks on the same object")));
    3659                 :             : 
    3660                 :             :         /* Mark the proclock to show we need to release this lockmode */
    3661         [ +  - ]:         907 :         if (locallock->nLocks > 0)
    3662                 :         907 :             locallock->proclock->releaseMask |= LOCKBIT_ON(locallock->tag.mode);
    3663                 :             : 
    3664                 :             :         /* And remove the locallock hashtable entry */
    3665                 :         907 :         RemoveLocalLock(locallock);
    3666                 :             :     }
    3667                 :             : 
    3668                 :             :     /*
    3669                 :             :      * Now, scan each lock partition separately.
    3670                 :             :      */
    3671         [ +  + ]:        5508 :     for (partition = 0; partition < NUM_LOCK_PARTITIONS; partition++)
    3672                 :             :     {
    3673                 :             :         LWLock     *partitionLock;
    3674                 :        5184 :         dlist_head *procLocks = &(MyProc->myProcLocks[partition]);
    3675                 :             :         dlist_mutable_iter proclock_iter;
    3676                 :             : 
    3677                 :        5184 :         partitionLock = LockHashPartitionLockByIndex(partition);
    3678                 :             : 
    3679                 :             :         /*
    3680                 :             :          * If the proclock list for this partition is empty, we can skip
    3681                 :             :          * acquiring the partition lock.  This optimization is safer than the
    3682                 :             :          * situation in LockReleaseAll, because we got rid of any fast-path
    3683                 :             :          * locks during AtPrepare_Locks, so there cannot be any case where
    3684                 :             :          * another backend is adding something to our lists now.  For safety,
    3685                 :             :          * though, we code this the same way as in LockReleaseAll.
    3686                 :             :          */
    3687         [ +  + ]:        5184 :         if (dlist_is_empty(procLocks))
    3688                 :        4380 :             continue;           /* needn't examine this partition */
    3689                 :             : 
    3690                 :         804 :         LWLockAcquire(partitionLock, LW_EXCLUSIVE);
    3691                 :             : 
    3692   [ +  -  +  + ]:        1659 :         dlist_foreach_modify(proclock_iter, procLocks)
    3693                 :             :         {
    3694                 :         855 :             proclock = dlist_container(PROCLOCK, procLink, proclock_iter.cur);
    3695                 :             : 
    3696                 :             :             Assert(proclock->tag.myProc == MyProc);
    3697                 :             : 
    3698                 :         855 :             lock = proclock->tag.myLock;
    3699                 :             : 
    3700                 :             :             /* Ignore VXID locks */
    3701         [ +  + ]:         855 :             if (lock->tag.locktag_type == LOCKTAG_VIRTUALTRANSACTION)
    3702                 :          31 :                 continue;
    3703                 :             : 
    3704                 :             :             PROCLOCK_PRINT("PostPrepare_Locks", proclock);
    3705                 :             :             LOCK_PRINT("PostPrepare_Locks", lock, 0);
    3706                 :             :             Assert(lock->nRequested >= 0);
    3707                 :             :             Assert(lock->nGranted >= 0);
    3708                 :             :             Assert(lock->nGranted <= lock->nRequested);
    3709                 :             :             Assert((proclock->holdMask & ~lock->grantMask) == 0);
    3710                 :             : 
    3711                 :             :             /* Ignore it if nothing to release (must be a session lock) */
    3712         [ +  + ]:         824 :             if (proclock->releaseMask == 0)
    3713                 :           8 :                 continue;
    3714                 :             : 
    3715                 :             :             /* Else we should be releasing all locks */
    3716         [ -  + ]:         816 :             if (proclock->releaseMask != proclock->holdMask)
    3717         [ #  # ]:           0 :                 elog(PANIC, "we seem to have dropped a bit somewhere");
    3718                 :             : 
    3719                 :             :             /*
    3720                 :             :              * We cannot simply modify proclock->tag.myProc to reassign
    3721                 :             :              * ownership of the lock, because that's part of the hash key and
    3722                 :             :              * the proclock would then be in the wrong hash chain.  Instead
    3723                 :             :              * use hash_update_hash_key.  (We used to create a new hash entry,
    3724                 :             :              * but that risks out-of-memory failure if other processes are
    3725                 :             :              * busy making proclocks too.)  We must unlink the proclock from
    3726                 :             :              * our procLink chain and put it into the new proc's chain, too.
    3727                 :             :              *
    3728                 :             :              * Note: the updated proclock hash key will still belong to the
    3729                 :             :              * same hash partition, cf proclock_hash().  So the partition lock
    3730                 :             :              * we already hold is sufficient for this.
    3731                 :             :              */
    3732                 :         816 :             dlist_delete(&proclock->procLink);
    3733                 :             : 
    3734                 :             :             /*
    3735                 :             :              * Create the new hash key for the proclock.
    3736                 :             :              */
    3737                 :         816 :             proclocktag.myLock = lock;
    3738                 :         816 :             proclocktag.myProc = newproc;
    3739                 :             : 
    3740                 :             :             /*
    3741                 :             :              * Update groupLeader pointer to point to the new proc.  (We'd
    3742                 :             :              * better not be a member of somebody else's lock group!)
    3743                 :             :              */
    3744                 :             :             Assert(proclock->groupLeader == proclock->tag.myProc);
    3745                 :         816 :             proclock->groupLeader = newproc;
    3746                 :             : 
    3747                 :             :             /*
    3748                 :             :              * Update the proclock.  We should not find any existing entry for
    3749                 :             :              * the same hash key, since there can be only one entry for any
    3750                 :             :              * given lock with my own proc.
    3751                 :             :              */
    3752         [ -  + ]:         816 :             if (!hash_update_hash_key(LockMethodProcLockHash,
    3753                 :             :                                       proclock,
    3754                 :             :                                       &proclocktag))
    3755         [ #  # ]:           0 :                 elog(PANIC, "duplicate entry found while reassigning a prepared transaction's locks");
    3756                 :             : 
    3757                 :             :             /* Re-link into the new proc's proclock list */
    3758                 :         816 :             dlist_push_tail(&newproc->myProcLocks[partition], &proclock->procLink);
    3759                 :             : 
    3760                 :             :             PROCLOCK_PRINT("PostPrepare_Locks: updated", proclock);
    3761                 :             :         }                       /* loop over PROCLOCKs within this partition */
    3762                 :             : 
    3763                 :         804 :         LWLockRelease(partitionLock);
    3764                 :             :     }                           /* loop over partitions */
    3765                 :             : 
    3766                 :         324 :     END_CRIT_SECTION();
    3767                 :         324 : }
    3768                 :             : 
    3769                 :             : 
    3770                 :             : /*
    3771                 :             :  * GetLockStatusData - Return a summary of the lock manager's internal
    3772                 :             :  * status, for use in a user-level reporting function.
    3773                 :             :  *
    3774                 :             :  * The return data consists of an array of LockInstanceData objects,
    3775                 :             :  * which are a lightly abstracted version of the PROCLOCK data structures,
    3776                 :             :  * i.e. there is one entry for each unique lock and interested PGPROC.
    3777                 :             :  * It is the caller's responsibility to match up related items (such as
    3778                 :             :  * references to the same lockable object or PGPROC) if wanted.
    3779                 :             :  *
    3780                 :             :  * The design goal is to hold the LWLocks for as short a time as possible;
    3781                 :             :  * thus, this function simply makes a copy of the necessary data and releases
    3782                 :             :  * the locks, allowing the caller to contemplate and format the data for as
    3783                 :             :  * long as it pleases.
    3784                 :             :  */
    3785                 :             : LockData *
    3786                 :         297 : GetLockStatusData(void)
    3787                 :             : {
    3788                 :             :     LockData   *data;
    3789                 :             :     PROCLOCK   *proclock;
    3790                 :             :     HASH_SEQ_STATUS seqstat;
    3791                 :             :     int         els;
    3792                 :             :     int         el;
    3793                 :             : 
    3794                 :         297 :     data = palloc_object(LockData);
    3795                 :             : 
    3796                 :             :     /* Guess how much space we'll need. */
    3797                 :         297 :     els = MaxBackends;
    3798                 :         297 :     el = 0;
    3799                 :         297 :     data->locks = palloc_array(LockInstanceData, els);
    3800                 :             : 
    3801                 :             :     /*
    3802                 :             :      * First, we iterate through the per-backend fast-path arrays, locking
    3803                 :             :      * them one at a time.  This might produce an inconsistent picture of the
    3804                 :             :      * system state, but taking all of those LWLocks at the same time seems
    3805                 :             :      * impractical (in particular, note MAX_SIMUL_LWLOCKS).  It shouldn't
    3806                 :             :      * matter too much, because none of these locks can be involved in lock
    3807                 :             :      * conflicts anyway - anything that might must be present in the main lock
    3808                 :             :      * table.  (For the same reason, we don't sweat about making leaderPid
    3809                 :             :      * completely valid.  We cannot safely dereference another backend's
    3810                 :             :      * lockGroupLeader field without holding all lock partition locks, and
    3811                 :             :      * it's not worth that.)
    3812                 :             :      */
    3813         [ +  + ]:       44159 :     for (uint32 i = 0; i < ProcGlobal->allProcCount; ++i)
    3814                 :             :     {
    3815                 :       43862 :         PGPROC     *proc = GetPGProcByNumber(i);
    3816                 :             : 
    3817                 :             :         /* Skip backends with pid=0, as they don't hold fast-path locks */
    3818         [ +  + ]:       43862 :         if (proc->pid == 0)
    3819                 :       39641 :             continue;
    3820                 :             : 
    3821                 :        4221 :         LWLockAcquire(&proc->fpInfoLock, LW_SHARED);
    3822                 :             : 
    3823         [ +  + ]:       37989 :         for (uint32 g = 0; g < FastPathLockGroupsPerBackend; g++)
    3824                 :             :         {
    3825                 :             :             /* Skip groups without registered fast-path locks */
    3826         [ +  + ]:       33768 :             if (proc->fpLockBits[g] == 0)
    3827                 :       30924 :                 continue;
    3828                 :             : 
    3829         [ +  + ]:       48348 :             for (int j = 0; j < FP_LOCK_SLOTS_PER_GROUP; j++)
    3830                 :             :             {
    3831                 :             :                 LockInstanceData *instance;
    3832                 :       45504 :                 uint32      f = FAST_PATH_SLOT(g, j);
    3833                 :       45504 :                 uint32      lockbits = FAST_PATH_GET_BITS(proc, f);
    3834                 :             : 
    3835                 :             :                 /* Skip unallocated slots */
    3836         [ +  + ]:       45504 :                 if (!lockbits)
    3837                 :       41442 :                     continue;
    3838                 :             : 
    3839         [ +  + ]:        4062 :                 if (el >= els)
    3840                 :             :                 {
    3841                 :           4 :                     els += MaxBackends;
    3842                 :           4 :                     data->locks = (LockInstanceData *)
    3843                 :           4 :                         repalloc(data->locks, sizeof(LockInstanceData) * els);
    3844                 :             :                 }
    3845                 :             : 
    3846                 :        4062 :                 instance = &data->locks[el];
    3847                 :        4062 :                 SET_LOCKTAG_RELATION(instance->locktag, proc->databaseId,
    3848                 :             :                                      proc->fpRelId[f]);
    3849                 :        4062 :                 instance->holdMask = lockbits << FAST_PATH_LOCKNUMBER_OFFSET;
    3850                 :        4062 :                 instance->waitLockMode = NoLock;
    3851                 :        4062 :                 instance->vxid.procNumber = proc->vxid.procNumber;
    3852                 :        4062 :                 instance->vxid.localTransactionId = proc->vxid.lxid;
    3853                 :        4062 :                 instance->pid = proc->pid;
    3854                 :        4062 :                 instance->leaderPid = proc->pid;
    3855                 :        4062 :                 instance->fastpath = true;
    3856                 :             : 
    3857                 :             :                 /*
    3858                 :             :                  * Successfully taking fast path lock means there were no
    3859                 :             :                  * conflicting locks.
    3860                 :             :                  */
    3861                 :        4062 :                 instance->waitStart = 0;
    3862                 :             : 
    3863                 :        4062 :                 el++;
    3864                 :             :             }
    3865                 :             :         }
    3866                 :             : 
    3867         [ +  + ]:        4221 :         if (proc->fpVXIDLock)
    3868                 :             :         {
    3869                 :             :             VirtualTransactionId vxid;
    3870                 :             :             LockInstanceData *instance;
    3871                 :             : 
    3872         [ +  + ]:        1236 :             if (el >= els)
    3873                 :             :             {
    3874                 :           2 :                 els += MaxBackends;
    3875                 :           2 :                 data->locks = (LockInstanceData *)
    3876                 :           2 :                     repalloc(data->locks, sizeof(LockInstanceData) * els);
    3877                 :             :             }
    3878                 :             : 
    3879                 :        1236 :             vxid.procNumber = proc->vxid.procNumber;
    3880                 :        1236 :             vxid.localTransactionId = proc->fpLocalTransactionId;
    3881                 :             : 
    3882                 :        1236 :             instance = &data->locks[el];
    3883                 :        1236 :             SET_LOCKTAG_VIRTUALTRANSACTION(instance->locktag, vxid);
    3884                 :        1236 :             instance->holdMask = LOCKBIT_ON(ExclusiveLock);
    3885                 :        1236 :             instance->waitLockMode = NoLock;
    3886                 :        1236 :             instance->vxid.procNumber = proc->vxid.procNumber;
    3887                 :        1236 :             instance->vxid.localTransactionId = proc->vxid.lxid;
    3888                 :        1236 :             instance->pid = proc->pid;
    3889                 :        1236 :             instance->leaderPid = proc->pid;
    3890                 :        1236 :             instance->fastpath = true;
    3891                 :        1236 :             instance->waitStart = 0;
    3892                 :             : 
    3893                 :        1236 :             el++;
    3894                 :             :         }
    3895                 :             : 
    3896                 :        4221 :         LWLockRelease(&proc->fpInfoLock);
    3897                 :             :     }
    3898                 :             : 
    3899                 :             :     /*
    3900                 :             :      * Next, acquire lock on the entire shared lock data structure.  We do
    3901                 :             :      * this so that, at least for locks in the primary lock table, the state
    3902                 :             :      * will be self-consistent.
    3903                 :             :      *
    3904                 :             :      * Since this is a read-only operation, we take shared instead of
    3905                 :             :      * exclusive lock.  There's not a whole lot of point to this, because all
    3906                 :             :      * the normal operations require exclusive lock, but it doesn't hurt
    3907                 :             :      * anything either. It will at least allow two backends to do
    3908                 :             :      * GetLockStatusData in parallel.
    3909                 :             :      *
    3910                 :             :      * Must grab LWLocks in partition-number order to avoid LWLock deadlock.
    3911                 :             :      */
    3912         [ +  + ]:        5049 :     for (int i = 0; i < NUM_LOCK_PARTITIONS; i++)
    3913                 :        4752 :         LWLockAcquire(LockHashPartitionLockByIndex(i), LW_SHARED);
    3914                 :             : 
    3915                 :             :     /* Now we can safely count the number of proclocks */
    3916                 :         297 :     data->nelements = el + hash_get_num_entries(LockMethodProcLockHash);
    3917         [ +  + ]:         297 :     if (data->nelements > els)
    3918                 :             :     {
    3919                 :          11 :         els = data->nelements;
    3920                 :          11 :         data->locks = (LockInstanceData *)
    3921                 :          11 :             repalloc(data->locks, sizeof(LockInstanceData) * els);
    3922                 :             :     }
    3923                 :             : 
    3924                 :             :     /* Now scan the tables to copy the data */
    3925                 :         297 :     hash_seq_init(&seqstat, LockMethodProcLockHash);
    3926                 :             : 
    3927         [ +  + ]:        2917 :     while ((proclock = (PROCLOCK *) hash_seq_search(&seqstat)))
    3928                 :             :     {
    3929                 :        2620 :         PGPROC     *proc = proclock->tag.myProc;
    3930                 :        2620 :         LOCK       *lock = proclock->tag.myLock;
    3931                 :        2620 :         LockInstanceData *instance = &data->locks[el];
    3932                 :             : 
    3933                 :        2620 :         memcpy(&instance->locktag, &lock->tag, sizeof(LOCKTAG));
    3934                 :        2620 :         instance->holdMask = proclock->holdMask;
    3935         [ +  + ]:        2620 :         if (proc->waitLock == proclock->tag.myLock)
    3936                 :          11 :             instance->waitLockMode = proc->waitLockMode;
    3937                 :             :         else
    3938                 :        2609 :             instance->waitLockMode = NoLock;
    3939                 :        2620 :         instance->vxid.procNumber = proc->vxid.procNumber;
    3940                 :        2620 :         instance->vxid.localTransactionId = proc->vxid.lxid;
    3941                 :        2620 :         instance->pid = proc->pid;
    3942                 :        2620 :         instance->leaderPid = proclock->groupLeader->pid;
    3943                 :        2620 :         instance->fastpath = false;
    3944                 :        2620 :         instance->waitStart = (TimestampTz) pg_atomic_read_u64(&proc->waitStart);
    3945                 :             : 
    3946                 :        2620 :         el++;
    3947                 :             :     }
    3948                 :             : 
    3949                 :             :     /*
    3950                 :             :      * And release locks.  We do this in reverse order for two reasons: (1)
    3951                 :             :      * Anyone else who needs more than one of the locks will be trying to lock
    3952                 :             :      * them in increasing order; we don't want to release the other process
    3953                 :             :      * until it can get all the locks it needs. (2) This avoids O(N^2)
    3954                 :             :      * behavior inside LWLockRelease.
    3955                 :             :      */
    3956         [ +  + ]:        5049 :     for (int i = NUM_LOCK_PARTITIONS; --i >= 0;)
    3957                 :        4752 :         LWLockRelease(LockHashPartitionLockByIndex(i));
    3958                 :             : 
    3959                 :             :     Assert(el == data->nelements);
    3960                 :             : 
    3961                 :         297 :     return data;
    3962                 :             : }
    3963                 :             : 
    3964                 :             : /*
    3965                 :             :  * GetBlockerStatusData - Return a summary of the lock manager's state
    3966                 :             :  * concerning locks that are blocking the specified PID or any member of
    3967                 :             :  * the PID's lock group, for use in a user-level reporting function.
    3968                 :             :  *
    3969                 :             :  * For each PID within the lock group that is awaiting some heavyweight lock,
    3970                 :             :  * the return data includes an array of LockInstanceData objects, which are
    3971                 :             :  * the same data structure used by GetLockStatusData; but unlike that function,
    3972                 :             :  * this one reports only the PROCLOCKs associated with the lock that that PID
    3973                 :             :  * is blocked on.  (Hence, all the locktags should be the same for any one
    3974                 :             :  * blocked PID.)  In addition, we return an array of the PIDs of those backends
    3975                 :             :  * that are ahead of the blocked PID in the lock's wait queue.  These can be
    3976                 :             :  * compared with the PIDs in the LockInstanceData objects to determine which
    3977                 :             :  * waiters are ahead of or behind the blocked PID in the queue.
    3978                 :             :  *
    3979                 :             :  * If blocked_pid isn't a valid backend PID or nothing in its lock group is
    3980                 :             :  * waiting on any heavyweight lock, return empty arrays.
    3981                 :             :  *
    3982                 :             :  * The design goal is to hold the LWLocks for as short a time as possible;
    3983                 :             :  * thus, this function simply makes a copy of the necessary data and releases
    3984                 :             :  * the locks, allowing the caller to contemplate and format the data for as
    3985                 :             :  * long as it pleases.
    3986                 :             :  */
    3987                 :             : BlockedProcsData *
    3988                 :        1742 : GetBlockerStatusData(int blocked_pid)
    3989                 :             : {
    3990                 :             :     BlockedProcsData *data;
    3991                 :             :     PGPROC     *proc;
    3992                 :             :     int         i;
    3993                 :             : 
    3994                 :        1742 :     data = palloc_object(BlockedProcsData);
    3995                 :             : 
    3996                 :             :     /*
    3997                 :             :      * Guess how much space we'll need, and preallocate.  Most of the time
    3998                 :             :      * this will avoid needing to do repalloc while holding the LWLocks.  (We
    3999                 :             :      * assume, but check with an Assert, that MaxBackends is enough entries
    4000                 :             :      * for the procs[] array; the other two could need enlargement, though.)
    4001                 :             :      */
    4002                 :        1742 :     data->nprocs = data->nlocks = data->npids = 0;
    4003                 :        1742 :     data->maxprocs = data->maxlocks = data->maxpids = MaxBackends;
    4004                 :        1742 :     data->procs = palloc_array(BlockedProcData, data->maxprocs);
    4005                 :        1742 :     data->locks = palloc_array(LockInstanceData, data->maxlocks);
    4006                 :        1742 :     data->waiter_pids = palloc_array(int, data->maxpids);
    4007                 :             : 
    4008                 :             :     /*
    4009                 :             :      * In order to search the ProcArray for blocked_pid and assume that that
    4010                 :             :      * entry won't immediately disappear under us, we must hold ProcArrayLock.
    4011                 :             :      * In addition, to examine the lock grouping fields of any other backend,
    4012                 :             :      * we must hold all the hash partition locks.  (Only one of those locks is
    4013                 :             :      * actually relevant for any one lock group, but we can't know which one
    4014                 :             :      * ahead of time.)  It's fairly annoying to hold all those locks
    4015                 :             :      * throughout this, but it's no worse than GetLockStatusData(), and it
    4016                 :             :      * does have the advantage that we're guaranteed to return a
    4017                 :             :      * self-consistent instantaneous state.
    4018                 :             :      */
    4019                 :        1742 :     LWLockAcquire(ProcArrayLock, LW_SHARED);
    4020                 :             : 
    4021                 :        1742 :     proc = BackendPidGetProcWithLock(blocked_pid);
    4022                 :             : 
    4023                 :             :     /* Nothing to do if it's gone */
    4024         [ +  - ]:        1742 :     if (proc != NULL)
    4025                 :             :     {
    4026                 :             :         /*
    4027                 :             :          * Acquire lock on the entire shared lock data structure.  See notes
    4028                 :             :          * in GetLockStatusData().
    4029                 :             :          */
    4030         [ +  + ]:       29614 :         for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
    4031                 :       27872 :             LWLockAcquire(LockHashPartitionLockByIndex(i), LW_SHARED);
    4032                 :             : 
    4033         [ +  + ]:        1742 :         if (proc->lockGroupLeader == NULL)
    4034                 :             :         {
    4035                 :             :             /* Easy case, proc is not a lock group member */
    4036                 :        1578 :             GetSingleProcBlockerStatusData(proc, data);
    4037                 :             :         }
    4038                 :             :         else
    4039                 :             :         {
    4040                 :             :             /* Examine all procs in proc's lock group */
    4041                 :             :             dlist_iter  iter;
    4042                 :             : 
    4043   [ +  -  +  + ]:         388 :             dlist_foreach(iter, &proc->lockGroupLeader->lockGroupMembers)
    4044                 :             :             {
    4045                 :             :                 PGPROC     *memberProc;
    4046                 :             : 
    4047                 :         224 :                 memberProc = dlist_container(PGPROC, lockGroupLink, iter.cur);
    4048                 :         224 :                 GetSingleProcBlockerStatusData(memberProc, data);
    4049                 :             :             }
    4050                 :             :         }
    4051                 :             : 
    4052                 :             :         /*
    4053                 :             :          * And release locks.  See notes in GetLockStatusData().
    4054                 :             :          */
    4055         [ +  + ]:       29614 :         for (i = NUM_LOCK_PARTITIONS; --i >= 0;)
    4056                 :       27872 :             LWLockRelease(LockHashPartitionLockByIndex(i));
    4057                 :             : 
    4058                 :             :         Assert(data->nprocs <= data->maxprocs);
    4059                 :             :     }
    4060                 :             : 
    4061                 :        1742 :     LWLockRelease(ProcArrayLock);
    4062                 :             : 
    4063                 :        1742 :     return data;
    4064                 :             : }
    4065                 :             : 
    4066                 :             : /* Accumulate data about one possibly-blocked proc for GetBlockerStatusData */
    4067                 :             : static void
    4068                 :        1802 : GetSingleProcBlockerStatusData(PGPROC *blocked_proc, BlockedProcsData *data)
    4069                 :             : {
    4070                 :        1802 :     LOCK       *theLock = blocked_proc->waitLock;
    4071                 :             :     BlockedProcData *bproc;
    4072                 :             :     dlist_iter  proclock_iter;
    4073                 :             :     dlist_iter  proc_iter;
    4074                 :             :     dclist_head *waitQueue;
    4075                 :             :     int         queue_size;
    4076                 :             : 
    4077                 :             :     /* Nothing to do if this proc is not blocked */
    4078         [ +  + ]:        1802 :     if (theLock == NULL)
    4079                 :         515 :         return;
    4080                 :             : 
    4081                 :             :     /* Set up a procs[] element */
    4082                 :        1287 :     bproc = &data->procs[data->nprocs++];
    4083                 :        1287 :     bproc->pid = blocked_proc->pid;
    4084                 :        1287 :     bproc->first_lock = data->nlocks;
    4085                 :        1287 :     bproc->first_waiter = data->npids;
    4086                 :             : 
    4087                 :             :     /*
    4088                 :             :      * We may ignore the proc's fast-path arrays, since nothing in those could
    4089                 :             :      * be related to a contended lock.
    4090                 :             :      */
    4091                 :             : 
    4092                 :             :     /* Collect all PROCLOCKs associated with theLock */
    4093   [ +  -  +  + ]:        3908 :     dlist_foreach(proclock_iter, &theLock->procLocks)
    4094                 :             :     {
    4095                 :        2621 :         PROCLOCK   *proclock =
    4096                 :        2621 :             dlist_container(PROCLOCK, lockLink, proclock_iter.cur);
    4097                 :        2621 :         PGPROC     *proc = proclock->tag.myProc;
    4098                 :        2621 :         LOCK       *lock = proclock->tag.myLock;
    4099                 :             :         LockInstanceData *instance;
    4100                 :             : 
    4101         [ -  + ]:        2621 :         if (data->nlocks >= data->maxlocks)
    4102                 :             :         {
    4103                 :           0 :             data->maxlocks += MaxBackends;
    4104                 :           0 :             data->locks = (LockInstanceData *)
    4105                 :           0 :                 repalloc(data->locks, sizeof(LockInstanceData) * data->maxlocks);
    4106                 :             :         }
    4107                 :             : 
    4108                 :        2621 :         instance = &data->locks[data->nlocks];
    4109                 :        2621 :         memcpy(&instance->locktag, &lock->tag, sizeof(LOCKTAG));
    4110                 :        2621 :         instance->holdMask = proclock->holdMask;
    4111         [ +  + ]:        2621 :         if (proc->waitLock == lock)
    4112                 :        1329 :             instance->waitLockMode = proc->waitLockMode;
    4113                 :             :         else
    4114                 :        1292 :             instance->waitLockMode = NoLock;
    4115                 :        2621 :         instance->vxid.procNumber = proc->vxid.procNumber;
    4116                 :        2621 :         instance->vxid.localTransactionId = proc->vxid.lxid;
    4117                 :        2621 :         instance->pid = proc->pid;
    4118                 :        2621 :         instance->leaderPid = proclock->groupLeader->pid;
    4119                 :        2621 :         instance->fastpath = false;
    4120                 :        2621 :         data->nlocks++;
    4121                 :             :     }
    4122                 :             : 
    4123                 :             :     /* Enlarge waiter_pids[] if it's too small to hold all wait queue PIDs */
    4124                 :        1287 :     waitQueue = &(theLock->waitProcs);
    4125                 :        1287 :     queue_size = dclist_count(waitQueue);
    4126                 :             : 
    4127         [ -  + ]:        1287 :     if (queue_size > data->maxpids - data->npids)
    4128                 :             :     {
    4129                 :           0 :         data->maxpids = Max(data->maxpids + MaxBackends,
    4130                 :             :                             data->npids + queue_size);
    4131                 :           0 :         data->waiter_pids = (int *) repalloc(data->waiter_pids,
    4132                 :           0 :                                              sizeof(int) * data->maxpids);
    4133                 :             :     }
    4134                 :             : 
    4135                 :             :     /* Collect PIDs from the lock's wait queue, stopping at blocked_proc */
    4136   [ +  -  +  - ]:        1307 :     dclist_foreach(proc_iter, waitQueue)
    4137                 :             :     {
    4138                 :        1307 :         PGPROC     *queued_proc = dlist_container(PGPROC, waitLink, proc_iter.cur);
    4139                 :             : 
    4140         [ +  + ]:        1307 :         if (queued_proc == blocked_proc)
    4141                 :        1287 :             break;
    4142                 :          20 :         data->waiter_pids[data->npids++] = queued_proc->pid;
    4143                 :             :     }
    4144                 :             : 
    4145                 :        1287 :     bproc->num_locks = data->nlocks - bproc->first_lock;
    4146                 :        1287 :     bproc->num_waiters = data->npids - bproc->first_waiter;
    4147                 :             : }
    4148                 :             : 
    4149                 :             : /*
    4150                 :             :  * Returns a list of currently held AccessExclusiveLocks, for use by
    4151                 :             :  * LogStandbySnapshot().  The result is a palloc'd array,
    4152                 :             :  * with the number of elements returned into *nlocks.
    4153                 :             :  *
    4154                 :             :  * XXX This currently takes a lock on all partitions of the lock table,
    4155                 :             :  * but it's possible to do better.  By reference counting locks and storing
    4156                 :             :  * the value in the ProcArray entry for each backend we could tell if any
    4157                 :             :  * locks need recording without having to acquire the partition locks and
    4158                 :             :  * scan the lock table.  Whether that's worth the additional overhead
    4159                 :             :  * is pretty dubious though.
    4160                 :             :  */
    4161                 :             : xl_standby_lock *
    4162                 :        1545 : GetRunningTransactionLocks(int *nlocks)
    4163                 :             : {
    4164                 :             :     xl_standby_lock *accessExclusiveLocks;
    4165                 :             :     PROCLOCK   *proclock;
    4166                 :             :     HASH_SEQ_STATUS seqstat;
    4167                 :             :     int         i;
    4168                 :             :     int         index;
    4169                 :             :     int         els;
    4170                 :             : 
    4171                 :             :     /*
    4172                 :             :      * Acquire lock on the entire shared lock data structure.
    4173                 :             :      *
    4174                 :             :      * Must grab LWLocks in partition-number order to avoid LWLock deadlock.
    4175                 :             :      */
    4176         [ +  + ]:       26265 :     for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
    4177                 :       24720 :         LWLockAcquire(LockHashPartitionLockByIndex(i), LW_SHARED);
    4178                 :             : 
    4179                 :             :     /* Now we can safely count the number of proclocks */
    4180                 :        1545 :     els = hash_get_num_entries(LockMethodProcLockHash);
    4181                 :             : 
    4182                 :             :     /*
    4183                 :             :      * Allocating enough space for all locks in the lock table is overkill,
    4184                 :             :      * but it's more convenient and faster than having to enlarge the array.
    4185                 :             :      */
    4186                 :        1545 :     accessExclusiveLocks = palloc(els * sizeof(xl_standby_lock));
    4187                 :             : 
    4188                 :             :     /* Now scan the tables to copy the data */
    4189                 :        1545 :     hash_seq_init(&seqstat, LockMethodProcLockHash);
    4190                 :             : 
    4191                 :             :     /*
    4192                 :             :      * If lock is a currently granted AccessExclusiveLock then it will have
    4193                 :             :      * just one proclock holder, so locks are never accessed twice in this
    4194                 :             :      * particular case. Don't copy this code for use elsewhere because in the
    4195                 :             :      * general case this will give you duplicate locks when looking at
    4196                 :             :      * non-exclusive lock types.
    4197                 :             :      */
    4198                 :        1545 :     index = 0;
    4199         [ +  + ]:        7150 :     while ((proclock = (PROCLOCK *) hash_seq_search(&seqstat)))
    4200                 :             :     {
    4201                 :             :         /* make sure this definition matches the one used in LockAcquire */
    4202         [ +  + ]:        5605 :         if ((proclock->holdMask & LOCKBIT_ON(AccessExclusiveLock)) &&
    4203         [ +  + ]:        2513 :             proclock->tag.myLock->tag.locktag_type == LOCKTAG_RELATION)
    4204                 :             :         {
    4205                 :        1761 :             PGPROC     *proc = proclock->tag.myProc;
    4206                 :        1761 :             LOCK       *lock = proclock->tag.myLock;
    4207                 :        1761 :             TransactionId xid = proc->xid;
    4208                 :             : 
    4209                 :             :             /*
    4210                 :             :              * Don't record locks for transactions if we know they have
    4211                 :             :              * already issued their WAL record for commit but not yet released
    4212                 :             :              * lock. It is still possible that we see locks held by already
    4213                 :             :              * complete transactions, if they haven't yet zeroed their xids.
    4214                 :             :              */
    4215         [ +  + ]:        1761 :             if (!TransactionIdIsValid(xid))
    4216                 :           6 :                 continue;
    4217                 :             : 
    4218                 :        1755 :             accessExclusiveLocks[index].xid = xid;
    4219                 :        1755 :             accessExclusiveLocks[index].dbOid = lock->tag.locktag_field1;
    4220                 :        1755 :             accessExclusiveLocks[index].relOid = lock->tag.locktag_field2;
    4221                 :             : 
    4222                 :        1755 :             index++;
    4223                 :             :         }
    4224                 :             :     }
    4225                 :             : 
    4226                 :             :     Assert(index <= els);
    4227                 :             : 
    4228                 :             :     /*
    4229                 :             :      * And release locks.  We do this in reverse order for two reasons: (1)
    4230                 :             :      * Anyone else who needs more than one of the locks will be trying to lock
    4231                 :             :      * them in increasing order; we don't want to release the other process
    4232                 :             :      * until it can get all the locks it needs. (2) This avoids O(N^2)
    4233                 :             :      * behavior inside LWLockRelease.
    4234                 :             :      */
    4235         [ +  + ]:       26265 :     for (i = NUM_LOCK_PARTITIONS; --i >= 0;)
    4236                 :       24720 :         LWLockRelease(LockHashPartitionLockByIndex(i));
    4237                 :             : 
    4238                 :        1545 :     *nlocks = index;
    4239                 :        1545 :     return accessExclusiveLocks;
    4240                 :             : }
    4241                 :             : 
    4242                 :             : /* Provide the textual name of any lock mode */
    4243                 :             : const char *
    4244                 :       10430 : GetLockmodeName(LOCKMETHODID lockmethodid, LOCKMODE mode)
    4245                 :             : {
    4246                 :             :     Assert(lockmethodid > 0 && lockmethodid < lengthof(LockMethods));
    4247                 :             :     Assert(mode > 0 && mode <= LockMethods[lockmethodid]->numLockModes);
    4248                 :       10430 :     return LockMethods[lockmethodid]->lockModeNames[mode];
    4249                 :             : }
    4250                 :             : 
    4251                 :             : #ifdef LOCK_DEBUG
    4252                 :             : /*
    4253                 :             :  * Dump all locks in the given proc's myProcLocks lists.
    4254                 :             :  *
    4255                 :             :  * Caller is responsible for having acquired appropriate LWLocks.
    4256                 :             :  */
    4257                 :             : void
    4258                 :             : DumpLocks(PGPROC *proc)
    4259                 :             : {
    4260                 :             :     int         i;
    4261                 :             : 
    4262                 :             :     if (proc == NULL)
    4263                 :             :         return;
    4264                 :             : 
    4265                 :             :     if (proc->waitLock)
    4266                 :             :         LOCK_PRINT("DumpLocks: waiting on", proc->waitLock, 0);
    4267                 :             : 
    4268                 :             :     for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
    4269                 :             :     {
    4270                 :             :         dlist_head *procLocks = &proc->myProcLocks[i];
    4271                 :             :         dlist_iter  iter;
    4272                 :             : 
    4273                 :             :         dlist_foreach(iter, procLocks)
    4274                 :             :         {
    4275                 :             :             PROCLOCK   *proclock = dlist_container(PROCLOCK, procLink, iter.cur);
    4276                 :             :             LOCK       *lock = proclock->tag.myLock;
    4277                 :             : 
    4278                 :             :             Assert(proclock->tag.myProc == proc);
    4279                 :             :             PROCLOCK_PRINT("DumpLocks", proclock);
    4280                 :             :             LOCK_PRINT("DumpLocks", lock, 0);
    4281                 :             :         }
    4282                 :             :     }
    4283                 :             : }
    4284                 :             : 
    4285                 :             : /*
    4286                 :             :  * Dump all lmgr locks.
    4287                 :             :  *
    4288                 :             :  * Caller is responsible for having acquired appropriate LWLocks.
    4289                 :             :  */
    4290                 :             : void
    4291                 :             : DumpAllLocks(void)
    4292                 :             : {
    4293                 :             :     PGPROC     *proc;
    4294                 :             :     PROCLOCK   *proclock;
    4295                 :             :     LOCK       *lock;
    4296                 :             :     HASH_SEQ_STATUS status;
    4297                 :             : 
    4298                 :             :     proc = MyProc;
    4299                 :             : 
    4300                 :             :     if (proc && proc->waitLock)
    4301                 :             :         LOCK_PRINT("DumpAllLocks: waiting on", proc->waitLock, 0);
    4302                 :             : 
    4303                 :             :     hash_seq_init(&status, LockMethodProcLockHash);
    4304                 :             : 
    4305                 :             :     while ((proclock = (PROCLOCK *) hash_seq_search(&status)) != NULL)
    4306                 :             :     {
    4307                 :             :         PROCLOCK_PRINT("DumpAllLocks", proclock);
    4308                 :             : 
    4309                 :             :         lock = proclock->tag.myLock;
    4310                 :             :         if (lock)
    4311                 :             :             LOCK_PRINT("DumpAllLocks", lock, 0);
    4312                 :             :         else
    4313                 :             :             elog(LOG, "DumpAllLocks: proclock->tag.myLock = NULL");
    4314                 :             :     }
    4315                 :             : }
    4316                 :             : #endif                          /* LOCK_DEBUG */
    4317                 :             : 
    4318                 :             : /*
    4319                 :             :  * LOCK 2PC resource manager's routines
    4320                 :             :  */
    4321                 :             : 
    4322                 :             : /*
    4323                 :             :  * Re-acquire a lock belonging to a transaction that was prepared.
    4324                 :             :  *
    4325                 :             :  * Because this function is run at db startup, re-acquiring the locks should
    4326                 :             :  * never conflict with running transactions because there are none.  We
    4327                 :             :  * assume that the lock state represented by the stored 2PC files is legal.
    4328                 :             :  *
    4329                 :             :  * When switching from Hot Standby mode to normal operation, the locks will
    4330                 :             :  * be already held by the startup process. The locks are acquired for the new
    4331                 :             :  * procs without checking for conflicts, so we don't get a conflict between the
    4332                 :             :  * startup process and the dummy procs, even though we will momentarily have
    4333                 :             :  * a situation where two procs are holding the same AccessExclusiveLock,
    4334                 :             :  * which isn't normally possible because the conflict. If we're in standby
    4335                 :             :  * mode, but a recovery snapshot hasn't been established yet, it's possible
    4336                 :             :  * that some but not all of the locks are already held by the startup process.
    4337                 :             :  *
    4338                 :             :  * This approach is simple, but also a bit dangerous, because if there isn't
    4339                 :             :  * enough shared memory to acquire the locks, an error will be thrown, which
    4340                 :             :  * is promoted to FATAL and recovery will abort, bringing down postmaster.
    4341                 :             :  * A safer approach would be to transfer the locks like we do in
    4342                 :             :  * AtPrepare_Locks, but then again, in hot standby mode it's possible for
    4343                 :             :  * read-only backends to use up all the shared lock memory anyway, so that
    4344                 :             :  * replaying the WAL record that needs to acquire a lock will throw an error
    4345                 :             :  * and PANIC anyway.
    4346                 :             :  */
    4347                 :             : void
    4348                 :          96 : lock_twophase_recover(FullTransactionId fxid, uint16 info,
    4349                 :             :                       void *recdata, uint32 len)
    4350                 :             : {
    4351                 :          96 :     TwoPhaseLockRecord *rec = (TwoPhaseLockRecord *) recdata;
    4352                 :          96 :     PGPROC     *proc = TwoPhaseGetDummyProc(fxid, false);
    4353                 :             :     LOCKTAG    *locktag;
    4354                 :             :     LOCKMODE    lockmode;
    4355                 :             :     LOCKMETHODID lockmethodid;
    4356                 :             :     LOCK       *lock;
    4357                 :             :     PROCLOCK   *proclock;
    4358                 :             :     PROCLOCKTAG proclocktag;
    4359                 :             :     bool        found;
    4360                 :             :     uint32      hashcode;
    4361                 :             :     uint32      proclock_hashcode;
    4362                 :             :     int         partition;
    4363                 :             :     LWLock     *partitionLock;
    4364                 :             :     LockMethod  lockMethodTable;
    4365                 :             : 
    4366                 :             :     Assert(len == sizeof(TwoPhaseLockRecord));
    4367                 :          96 :     locktag = &rec->locktag;
    4368                 :          96 :     lockmode = rec->lockmode;
    4369                 :          96 :     lockmethodid = locktag->locktag_lockmethodid;
    4370                 :             : 
    4371   [ +  -  -  + ]:          96 :     if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
    4372         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock method: %d", lockmethodid);
    4373                 :          96 :     lockMethodTable = LockMethods[lockmethodid];
    4374                 :             : 
    4375                 :          96 :     hashcode = LockTagHashCode(locktag);
    4376                 :          96 :     partition = LockHashPartition(hashcode);
    4377                 :          96 :     partitionLock = LockHashPartitionLock(hashcode);
    4378                 :             : 
    4379                 :          96 :     LWLockAcquire(partitionLock, LW_EXCLUSIVE);
    4380                 :             : 
    4381                 :             :     /*
    4382                 :             :      * Find or create a lock with this tag.
    4383                 :             :      */
    4384                 :          96 :     lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
    4385                 :             :                                                 locktag,
    4386                 :             :                                                 hashcode,
    4387                 :             :                                                 HASH_ENTER_NULL,
    4388                 :             :                                                 &found);
    4389         [ -  + ]:          96 :     if (!lock)
    4390                 :             :     {
    4391                 :           0 :         LWLockRelease(partitionLock);
    4392         [ #  # ]:           0 :         ereport(ERROR,
    4393                 :             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    4394                 :             :                  errmsg("out of shared memory"),
    4395                 :             :                  errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
    4396                 :             :     }
    4397                 :             : 
    4398                 :             :     /*
    4399                 :             :      * if it's a new lock object, initialize it
    4400                 :             :      */
    4401         [ +  + ]:          96 :     if (!found)
    4402                 :             :     {
    4403                 :          84 :         lock->grantMask = 0;
    4404                 :          84 :         lock->waitMask = 0;
    4405                 :          84 :         dlist_init(&lock->procLocks);
    4406                 :          84 :         dclist_init(&lock->waitProcs);
    4407                 :          84 :         lock->nRequested = 0;
    4408                 :          84 :         lock->nGranted = 0;
    4409   [ +  -  +  -  :         504 :         MemSet(lock->requested, 0, sizeof(int) * MAX_LOCKMODES);
          +  -  +  -  +  
                      + ]
    4410   [ -  +  -  -  :          84 :         MemSet(lock->granted, 0, sizeof(int) * MAX_LOCKMODES);
          -  -  -  -  -  
                      - ]
    4411                 :             :         LOCK_PRINT("lock_twophase_recover: new", lock, lockmode);
    4412                 :             :     }
    4413                 :             :     else
    4414                 :             :     {
    4415                 :             :         LOCK_PRINT("lock_twophase_recover: found", lock, lockmode);
    4416                 :             :         Assert((lock->nRequested >= 0) && (lock->requested[lockmode] >= 0));
    4417                 :             :         Assert((lock->nGranted >= 0) && (lock->granted[lockmode] >= 0));
    4418                 :             :         Assert(lock->nGranted <= lock->nRequested);
    4419                 :             :     }
    4420                 :             : 
    4421                 :             :     /*
    4422                 :             :      * Create the hash key for the proclock table.
    4423                 :             :      */
    4424                 :          96 :     proclocktag.myLock = lock;
    4425                 :          96 :     proclocktag.myProc = proc;
    4426                 :             : 
    4427                 :          96 :     proclock_hashcode = ProcLockHashCode(&proclocktag, hashcode);
    4428                 :             : 
    4429                 :             :     /*
    4430                 :             :      * Find or create a proclock entry with this tag
    4431                 :             :      */
    4432                 :          96 :     proclock = (PROCLOCK *) hash_search_with_hash_value(LockMethodProcLockHash,
    4433                 :             :                                                         &proclocktag,
    4434                 :             :                                                         proclock_hashcode,
    4435                 :             :                                                         HASH_ENTER_NULL,
    4436                 :             :                                                         &found);
    4437         [ -  + ]:          96 :     if (!proclock)
    4438                 :             :     {
    4439                 :             :         /* Oops, not enough shmem for the proclock */
    4440         [ #  # ]:           0 :         if (lock->nRequested == 0)
    4441                 :             :         {
    4442                 :             :             /*
    4443                 :             :              * There are no other requestors of this lock, so garbage-collect
    4444                 :             :              * the lock object.  We *must* do this to avoid a permanent leak
    4445                 :             :              * of shared memory, because there won't be anything to cause
    4446                 :             :              * anyone to release the lock object later.
    4447                 :             :              */
    4448                 :             :             Assert(dlist_is_empty(&lock->procLocks));
    4449         [ #  # ]:           0 :             if (!hash_search_with_hash_value(LockMethodLockHash,
    4450                 :           0 :                                              &(lock->tag),
    4451                 :             :                                              hashcode,
    4452                 :             :                                              HASH_REMOVE,
    4453                 :             :                                              NULL))
    4454         [ #  # ]:           0 :                 elog(PANIC, "lock table corrupted");
    4455                 :             :         }
    4456                 :           0 :         LWLockRelease(partitionLock);
    4457         [ #  # ]:           0 :         ereport(ERROR,
    4458                 :             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    4459                 :             :                  errmsg("out of shared memory"),
    4460                 :             :                  errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
    4461                 :             :     }
    4462                 :             : 
    4463                 :             :     /*
    4464                 :             :      * If new, initialize the new entry
    4465                 :             :      */
    4466         [ +  + ]:          96 :     if (!found)
    4467                 :             :     {
    4468                 :             :         Assert(proc->lockGroupLeader == NULL);
    4469                 :          88 :         proclock->groupLeader = proc;
    4470                 :          88 :         proclock->holdMask = 0;
    4471                 :          88 :         proclock->releaseMask = 0;
    4472                 :             :         /* Add proclock to appropriate lists */
    4473                 :          88 :         dlist_push_tail(&lock->procLocks, &proclock->lockLink);
    4474                 :          88 :         dlist_push_tail(&proc->myProcLocks[partition],
    4475                 :             :                         &proclock->procLink);
    4476                 :             :         PROCLOCK_PRINT("lock_twophase_recover: new", proclock);
    4477                 :             :     }
    4478                 :             :     else
    4479                 :             :     {
    4480                 :             :         PROCLOCK_PRINT("lock_twophase_recover: found", proclock);
    4481                 :             :         Assert((proclock->holdMask & ~lock->grantMask) == 0);
    4482                 :             :     }
    4483                 :             : 
    4484                 :             :     /*
    4485                 :             :      * lock->nRequested and lock->requested[] count the total number of
    4486                 :             :      * requests, whether granted or waiting, so increment those immediately.
    4487                 :             :      */
    4488                 :          96 :     lock->nRequested++;
    4489                 :          96 :     lock->requested[lockmode]++;
    4490                 :             :     Assert((lock->nRequested > 0) && (lock->requested[lockmode] > 0));
    4491                 :             : 
    4492                 :             :     /*
    4493                 :             :      * We shouldn't already hold the desired lock.
    4494                 :             :      */
    4495         [ -  + ]:          96 :     if (proclock->holdMask & LOCKBIT_ON(lockmode))
    4496         [ #  # ]:           0 :         elog(ERROR, "lock %s on object %u/%u/%u is already held",
    4497                 :             :              lockMethodTable->lockModeNames[lockmode],
    4498                 :             :              lock->tag.locktag_field1, lock->tag.locktag_field2,
    4499                 :             :              lock->tag.locktag_field3);
    4500                 :             : 
    4501                 :             :     /*
    4502                 :             :      * We ignore any possible conflicts and just grant ourselves the lock. Not
    4503                 :             :      * only because we don't bother, but also to avoid deadlocks when
    4504                 :             :      * switching from standby to normal mode. See function comment.
    4505                 :             :      */
    4506                 :          96 :     GrantLock(lock, proclock, lockmode);
    4507                 :             : 
    4508                 :             :     /*
    4509                 :             :      * Bump strong lock count, to make sure any fast-path lock requests won't
    4510                 :             :      * be granted without consulting the primary lock table.
    4511                 :             :      */
    4512   [ +  -  +  +  :          96 :     if (ConflictsWithRelationFastPath(&lock->tag, lockmode))
             +  -  +  + ]
    4513                 :             :     {
    4514                 :          18 :         uint32      fasthashcode = FastPathStrongLockHashPartition(hashcode);
    4515                 :             : 
    4516                 :          18 :         SpinLockAcquire(&FastPathStrongRelationLocks->mutex);
    4517                 :          18 :         FastPathStrongRelationLocks->count[fasthashcode]++;
    4518                 :          18 :         SpinLockRelease(&FastPathStrongRelationLocks->mutex);
    4519                 :             :     }
    4520                 :             : 
    4521                 :          96 :     LWLockRelease(partitionLock);
    4522                 :          96 : }
    4523                 :             : 
    4524                 :             : /*
    4525                 :             :  * Re-acquire a lock belonging to a transaction that was prepared, when
    4526                 :             :  * starting up into hot standby mode.
    4527                 :             :  */
    4528                 :             : void
    4529                 :           0 : lock_twophase_standby_recover(FullTransactionId fxid, uint16 info,
    4530                 :             :                               void *recdata, uint32 len)
    4531                 :             : {
    4532                 :           0 :     TwoPhaseLockRecord *rec = (TwoPhaseLockRecord *) recdata;
    4533                 :             :     LOCKTAG    *locktag;
    4534                 :             :     LOCKMODE    lockmode;
    4535                 :             :     LOCKMETHODID lockmethodid;
    4536                 :             : 
    4537                 :             :     Assert(len == sizeof(TwoPhaseLockRecord));
    4538                 :           0 :     locktag = &rec->locktag;
    4539                 :           0 :     lockmode = rec->lockmode;
    4540                 :           0 :     lockmethodid = locktag->locktag_lockmethodid;
    4541                 :             : 
    4542   [ #  #  #  # ]:           0 :     if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
    4543         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock method: %d", lockmethodid);
    4544                 :             : 
    4545         [ #  # ]:           0 :     if (lockmode == AccessExclusiveLock &&
    4546         [ #  # ]:           0 :         locktag->locktag_type == LOCKTAG_RELATION)
    4547                 :             :     {
    4548                 :           0 :         StandbyAcquireAccessExclusiveLock(XidFromFullTransactionId(fxid),
    4549                 :             :                                           locktag->locktag_field1 /* dboid */ ,
    4550                 :             :                                           locktag->locktag_field2 /* reloid */ );
    4551                 :             :     }
    4552                 :           0 : }
    4553                 :             : 
    4554                 :             : 
    4555                 :             : /*
    4556                 :             :  * 2PC processing routine for COMMIT PREPARED case.
    4557                 :             :  *
    4558                 :             :  * Find and release the lock indicated by the 2PC record.
    4559                 :             :  */
    4560                 :             : void
    4561                 :         917 : lock_twophase_postcommit(FullTransactionId fxid, uint16 info,
    4562                 :             :                          void *recdata, uint32 len)
    4563                 :             : {
    4564                 :         917 :     TwoPhaseLockRecord *rec = (TwoPhaseLockRecord *) recdata;
    4565                 :         917 :     PGPROC     *proc = TwoPhaseGetDummyProc(fxid, true);
    4566                 :             :     LOCKTAG    *locktag;
    4567                 :             :     LOCKMETHODID lockmethodid;
    4568                 :             :     LockMethod  lockMethodTable;
    4569                 :             : 
    4570                 :             :     Assert(len == sizeof(TwoPhaseLockRecord));
    4571                 :         917 :     locktag = &rec->locktag;
    4572                 :         917 :     lockmethodid = locktag->locktag_lockmethodid;
    4573                 :             : 
    4574   [ +  -  -  + ]:         917 :     if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
    4575         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock method: %d", lockmethodid);
    4576                 :         917 :     lockMethodTable = LockMethods[lockmethodid];
    4577                 :             : 
    4578                 :         917 :     LockRefindAndRelease(lockMethodTable, proc, locktag, rec->lockmode, true);
    4579                 :         917 : }
    4580                 :             : 
    4581                 :             : /*
    4582                 :             :  * 2PC processing routine for ROLLBACK PREPARED case.
    4583                 :             :  *
    4584                 :             :  * This is actually just the same as the COMMIT case.
    4585                 :             :  */
    4586                 :             : void
    4587                 :         186 : lock_twophase_postabort(FullTransactionId fxid, uint16 info,
    4588                 :             :                         void *recdata, uint32 len)
    4589                 :             : {
    4590                 :         186 :     lock_twophase_postcommit(fxid, info, recdata, len);
    4591                 :         186 : }
    4592                 :             : 
    4593                 :             : /*
    4594                 :             :  *      VirtualXactLockTableInsert
    4595                 :             :  *
    4596                 :             :  *      Take vxid lock via the fast-path.  There can't be any pre-existing
    4597                 :             :  *      lockers, as we haven't advertised this vxid via the ProcArray yet.
    4598                 :             :  *
    4599                 :             :  *      Since MyProc->fpLocalTransactionId will normally contain the same data
    4600                 :             :  *      as MyProc->vxid.lxid, you might wonder if we really need both.  The
    4601                 :             :  *      difference is that MyProc->vxid.lxid is set and cleared unlocked, and
    4602                 :             :  *      examined by procarray.c, while fpLocalTransactionId is protected by
    4603                 :             :  *      fpInfoLock and is used only by the locking subsystem.  Doing it this
    4604                 :             :  *      way makes it easier to verify that there are no funny race conditions.
    4605                 :             :  *
    4606                 :             :  *      We don't bother recording this lock in the local lock table, since it's
    4607                 :             :  *      only ever released at the end of a transaction.  Instead,
    4608                 :             :  *      LockReleaseAll() calls VirtualXactLockTableCleanup().
    4609                 :             :  */
    4610                 :             : void
    4611                 :      670734 : VirtualXactLockTableInsert(VirtualTransactionId vxid)
    4612                 :             : {
    4613                 :             :     Assert(VirtualTransactionIdIsValid(vxid));
    4614                 :             : 
    4615                 :      670734 :     LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
    4616                 :             : 
    4617                 :             :     Assert(MyProc->vxid.procNumber == vxid.procNumber);
    4618                 :             :     Assert(MyProc->fpLocalTransactionId == InvalidLocalTransactionId);
    4619                 :             :     Assert(MyProc->fpVXIDLock == false);
    4620                 :             : 
    4621                 :      670734 :     MyProc->fpVXIDLock = true;
    4622                 :      670734 :     MyProc->fpLocalTransactionId = vxid.localTransactionId;
    4623                 :             : 
    4624                 :      670734 :     LWLockRelease(&MyProc->fpInfoLock);
    4625                 :      670734 : }
    4626                 :             : 
    4627                 :             : /*
    4628                 :             :  *      VirtualXactLockTableCleanup
    4629                 :             :  *
    4630                 :             :  *      Check whether a VXID lock has been materialized; if so, release it,
    4631                 :             :  *      unblocking waiters.
    4632                 :             :  */
    4633                 :             : void
    4634                 :      671296 : VirtualXactLockTableCleanup(void)
    4635                 :             : {
    4636                 :             :     bool        fastpath;
    4637                 :             :     LocalTransactionId lxid;
    4638                 :             : 
    4639                 :             :     Assert(MyProc->vxid.procNumber != INVALID_PROC_NUMBER);
    4640                 :             : 
    4641                 :             :     /*
    4642                 :             :      * Clean up shared memory state.
    4643                 :             :      */
    4644                 :      671296 :     LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
    4645                 :             : 
    4646                 :      671296 :     fastpath = MyProc->fpVXIDLock;
    4647                 :      671296 :     lxid = MyProc->fpLocalTransactionId;
    4648                 :      671296 :     MyProc->fpVXIDLock = false;
    4649                 :      671296 :     MyProc->fpLocalTransactionId = InvalidLocalTransactionId;
    4650                 :             : 
    4651                 :      671296 :     LWLockRelease(&MyProc->fpInfoLock);
    4652                 :             : 
    4653                 :             :     /*
    4654                 :             :      * If fpVXIDLock has been cleared without touching fpLocalTransactionId,
    4655                 :             :      * that means someone transferred the lock to the main lock table.
    4656                 :             :      */
    4657   [ +  +  +  + ]:      671296 :     if (!fastpath && LocalTransactionIdIsValid(lxid))
    4658                 :             :     {
    4659                 :             :         VirtualTransactionId vxid;
    4660                 :             :         LOCKTAG     locktag;
    4661                 :             : 
    4662                 :         290 :         vxid.procNumber = MyProcNumber;
    4663                 :         290 :         vxid.localTransactionId = lxid;
    4664                 :         290 :         SET_LOCKTAG_VIRTUALTRANSACTION(locktag, vxid);
    4665                 :             : 
    4666                 :         290 :         LockRefindAndRelease(LockMethods[DEFAULT_LOCKMETHOD], MyProc,
    4667                 :             :                              &locktag, ExclusiveLock, false);
    4668                 :             :     }
    4669                 :      671296 : }
    4670                 :             : 
    4671                 :             : /*
    4672                 :             :  *      XactLockForVirtualXact
    4673                 :             :  *
    4674                 :             :  * If TransactionIdIsValid(xid), this is essentially XactLockTableWait(xid,
    4675                 :             :  * NULL, NULL, XLTW_None) or ConditionalXactLockTableWait(xid).  Unlike those
    4676                 :             :  * functions, it assumes "xid" is never a subtransaction and that "xid" is
    4677                 :             :  * prepared, committed, or aborted.
    4678                 :             :  *
    4679                 :             :  * If !TransactionIdIsValid(xid), this locks every prepared XID having been
    4680                 :             :  * known as "vxid" before its PREPARE TRANSACTION.
    4681                 :             :  */
    4682                 :             : static bool
    4683                 :         311 : XactLockForVirtualXact(VirtualTransactionId vxid,
    4684                 :             :                        TransactionId xid, bool wait)
    4685                 :             : {
    4686                 :         311 :     bool        more = false;
    4687                 :             : 
    4688                 :             :     /* There is no point to wait for 2PCs if you have no 2PCs. */
    4689         [ +  + ]:         311 :     if (max_prepared_xacts == 0)
    4690                 :         137 :         return true;
    4691                 :             : 
    4692                 :             :     do
    4693                 :             :     {
    4694                 :             :         LockAcquireResult lar;
    4695                 :             :         LOCKTAG     tag;
    4696                 :             : 
    4697                 :             :         /* Clear state from previous iterations. */
    4698         [ -  + ]:         174 :         if (more)
    4699                 :             :         {
    4700                 :           0 :             xid = InvalidTransactionId;
    4701                 :           0 :             more = false;
    4702                 :             :         }
    4703                 :             : 
    4704                 :             :         /* If we have no xid, try to find one. */
    4705         [ +  + ]:         174 :         if (!TransactionIdIsValid(xid))
    4706                 :          88 :             xid = TwoPhaseGetXidByVirtualXID(vxid, &more);
    4707         [ +  + ]:         174 :         if (!TransactionIdIsValid(xid))
    4708                 :             :         {
    4709                 :             :             Assert(!more);
    4710                 :          75 :             return true;
    4711                 :             :         }
    4712                 :             : 
    4713                 :             :         /* Check or wait for XID completion. */
    4714                 :          99 :         SET_LOCKTAG_TRANSACTION(tag, xid);
    4715                 :          99 :         lar = LockAcquire(&tag, ShareLock, false, !wait);
    4716         [ -  + ]:          99 :         if (lar == LOCKACQUIRE_NOT_AVAIL)
    4717                 :           0 :             return false;
    4718                 :          99 :         LockRelease(&tag, ShareLock, false);
    4719         [ -  + ]:          99 :     } while (more);
    4720                 :             : 
    4721                 :          99 :     return true;
    4722                 :             : }
    4723                 :             : 
    4724                 :             : /*
    4725                 :             :  *      VirtualXactLock
    4726                 :             :  *
    4727                 :             :  * If wait = true, wait as long as the given VXID or any XID acquired by the
    4728                 :             :  * same transaction is still running.  Then, return true.
    4729                 :             :  *
    4730                 :             :  * If wait = false, just check whether that VXID or one of those XIDs is still
    4731                 :             :  * running, and return true or false.
    4732                 :             :  */
    4733                 :             : bool
    4734                 :         351 : VirtualXactLock(VirtualTransactionId vxid, bool wait)
    4735                 :             : {
    4736                 :             :     LOCKTAG     tag;
    4737                 :             :     PGPROC     *proc;
    4738                 :         351 :     TransactionId xid = InvalidTransactionId;
    4739                 :             : 
    4740                 :             :     Assert(VirtualTransactionIdIsValid(vxid));
    4741                 :             : 
    4742         [ +  + ]:         351 :     if (VirtualTransactionIdIsRecoveredPreparedXact(vxid))
    4743                 :             :         /* no vxid lock; localTransactionId is a normal, locked XID */
    4744                 :           1 :         return XactLockForVirtualXact(vxid, vxid.localTransactionId, wait);
    4745                 :             : 
    4746                 :         350 :     SET_LOCKTAG_VIRTUALTRANSACTION(tag, vxid);
    4747                 :             : 
    4748                 :             :     /*
    4749                 :             :      * If a lock table entry must be made, this is the PGPROC on whose behalf
    4750                 :             :      * it must be done.  Note that the transaction might end or the PGPROC
    4751                 :             :      * might be reassigned to a new backend before we get around to examining
    4752                 :             :      * it, but it doesn't matter.  If we find upon examination that the
    4753                 :             :      * relevant lxid is no longer running here, that's enough to prove that
    4754                 :             :      * it's no longer running anywhere.
    4755                 :             :      */
    4756                 :         350 :     proc = ProcNumberGetProc(vxid.procNumber);
    4757         [ +  + ]:         350 :     if (proc == NULL)
    4758                 :           3 :         return XactLockForVirtualXact(vxid, InvalidTransactionId, wait);
    4759                 :             : 
    4760                 :             :     /*
    4761                 :             :      * We must acquire this lock before checking the procNumber and lxid
    4762                 :             :      * against the ones we're waiting for.  The target backend will only set
    4763                 :             :      * or clear lxid while holding this lock.
    4764                 :             :      */
    4765                 :         347 :     LWLockAcquire(&proc->fpInfoLock, LW_EXCLUSIVE);
    4766                 :             : 
    4767         [ +  - ]:         347 :     if (proc->vxid.procNumber != vxid.procNumber
    4768         [ +  + ]:         347 :         || proc->fpLocalTransactionId != vxid.localTransactionId)
    4769                 :             :     {
    4770                 :             :         /* VXID ended */
    4771                 :          33 :         LWLockRelease(&proc->fpInfoLock);
    4772                 :          33 :         return XactLockForVirtualXact(vxid, InvalidTransactionId, wait);
    4773                 :             :     }
    4774                 :             : 
    4775                 :             :     /*
    4776                 :             :      * If we aren't asked to wait, there's no need to set up a lock table
    4777                 :             :      * entry.  The transaction is still in progress, so just return false.
    4778                 :             :      */
    4779         [ +  + ]:         314 :     if (!wait)
    4780                 :             :     {
    4781                 :          15 :         LWLockRelease(&proc->fpInfoLock);
    4782                 :          15 :         return false;
    4783                 :             :     }
    4784                 :             : 
    4785                 :             :     /*
    4786                 :             :      * OK, we're going to need to sleep on the VXID.  But first, we must set
    4787                 :             :      * up the primary lock table entry, if needed (ie, convert the proc's
    4788                 :             :      * fast-path lock on its VXID to a regular lock).
    4789                 :             :      */
    4790         [ +  + ]:         299 :     if (proc->fpVXIDLock)
    4791                 :             :     {
    4792                 :             :         PROCLOCK   *proclock;
    4793                 :             :         uint32      hashcode;
    4794                 :             :         LWLock     *partitionLock;
    4795                 :             : 
    4796                 :         290 :         hashcode = LockTagHashCode(&tag);
    4797                 :             : 
    4798                 :         290 :         partitionLock = LockHashPartitionLock(hashcode);
    4799                 :         290 :         LWLockAcquire(partitionLock, LW_EXCLUSIVE);
    4800                 :             : 
    4801                 :         290 :         proclock = SetupLockInTable(LockMethods[DEFAULT_LOCKMETHOD], proc,
    4802                 :             :                                     &tag, hashcode, ExclusiveLock);
    4803         [ -  + ]:         290 :         if (!proclock)
    4804                 :             :         {
    4805                 :           0 :             LWLockRelease(partitionLock);
    4806                 :           0 :             LWLockRelease(&proc->fpInfoLock);
    4807         [ #  # ]:           0 :             ereport(ERROR,
    4808                 :             :                     (errcode(ERRCODE_OUT_OF_MEMORY),
    4809                 :             :                      errmsg("out of shared memory"),
    4810                 :             :                      errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
    4811                 :             :         }
    4812                 :         290 :         GrantLock(proclock->tag.myLock, proclock, ExclusiveLock);
    4813                 :             : 
    4814                 :         290 :         LWLockRelease(partitionLock);
    4815                 :             : 
    4816                 :         290 :         proc->fpVXIDLock = false;
    4817                 :             :     }
    4818                 :             : 
    4819                 :             :     /*
    4820                 :             :      * If the proc has an XID now, we'll avoid a TwoPhaseGetXidByVirtualXID()
    4821                 :             :      * search.  The proc might have assigned this XID but not yet locked it,
    4822                 :             :      * in which case the proc will lock this XID before releasing the VXID.
    4823                 :             :      * The fpInfoLock critical section excludes VirtualXactLockTableCleanup(),
    4824                 :             :      * so we won't save an XID of a different VXID.  It doesn't matter whether
    4825                 :             :      * we save this before or after setting up the primary lock table entry.
    4826                 :             :      */
    4827                 :         299 :     xid = proc->xid;
    4828                 :             : 
    4829                 :             :     /* Done with proc->fpLockBits */
    4830                 :         299 :     LWLockRelease(&proc->fpInfoLock);
    4831                 :             : 
    4832                 :             :     /* Time to wait. */
    4833                 :         299 :     (void) LockAcquire(&tag, ShareLock, false, false);
    4834                 :             : 
    4835                 :         274 :     LockRelease(&tag, ShareLock, false);
    4836                 :         274 :     return XactLockForVirtualXact(vxid, xid, wait);
    4837                 :             : }
    4838                 :             : 
    4839                 :             : /*
    4840                 :             :  * LockWaiterCount
    4841                 :             :  *
    4842                 :             :  * Find the number of lock requester on this locktag
    4843                 :             :  */
    4844                 :             : int
    4845                 :       95158 : LockWaiterCount(const LOCKTAG *locktag)
    4846                 :             : {
    4847                 :       95158 :     LOCKMETHODID lockmethodid = locktag->locktag_lockmethodid;
    4848                 :             :     LOCK       *lock;
    4849                 :             :     bool        found;
    4850                 :             :     uint32      hashcode;
    4851                 :             :     LWLock     *partitionLock;
    4852                 :       95158 :     int         waiters = 0;
    4853                 :             : 
    4854   [ +  -  -  + ]:       95158 :     if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
    4855         [ #  # ]:           0 :         elog(ERROR, "unrecognized lock method: %d", lockmethodid);
    4856                 :             : 
    4857                 :       95158 :     hashcode = LockTagHashCode(locktag);
    4858                 :       95158 :     partitionLock = LockHashPartitionLock(hashcode);
    4859                 :       95158 :     LWLockAcquire(partitionLock, LW_EXCLUSIVE);
    4860                 :             : 
    4861                 :       95158 :     lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
    4862                 :             :                                                 locktag,
    4863                 :             :                                                 hashcode,
    4864                 :             :                                                 HASH_FIND,
    4865                 :             :                                                 &found);
    4866         [ +  + ]:       95158 :     if (found)
    4867                 :             :     {
    4868                 :             :         Assert(lock != NULL);
    4869                 :          15 :         waiters = lock->nRequested;
    4870                 :             :     }
    4871                 :       95158 :     LWLockRelease(partitionLock);
    4872                 :             : 
    4873                 :       95158 :     return waiters;
    4874                 :             : }
        

Generated by: LCOV version 2.0-1