LCOV - code coverage report
Current view: top level - src/backend/storage/ipc - standby.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 91.0 % 388 353
Test Date: 2026-12-03 23:16:08 Functions: 100.0 % 31 31
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 71.4 % 199 142

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * standby.c
       4                 :             :  *    Misc functions used in Hot Standby mode.
       5                 :             :  *
       6                 :             :  *  All functions for handling RM_STANDBY_ID, which relate to
       7                 :             :  *  AccessExclusiveLocks and starting snapshots for Hot Standby mode.
       8                 :             :  *  Plus conflict recovery processing.
       9                 :             :  *
      10                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      11                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
      12                 :             :  *
      13                 :             :  * IDENTIFICATION
      14                 :             :  *    src/backend/storage/ipc/standby.c
      15                 :             :  *
      16                 :             :  *-------------------------------------------------------------------------
      17                 :             :  */
      18                 :             : #include "postgres.h"
      19                 :             : #include "access/transam.h"
      20                 :             : #include "access/twophase.h"
      21                 :             : #include "access/xact.h"
      22                 :             : #include "access/xloginsert.h"
      23                 :             : #include "access/xlogrecovery.h"
      24                 :             : #include "access/xlogutils.h"
      25                 :             : #include "miscadmin.h"
      26                 :             : #include "pgstat.h"
      27                 :             : #include "replication/slot.h"
      28                 :             : #include "storage/bufmgr.h"
      29                 :             : #include "storage/latch.h"
      30                 :             : #include "storage/proc.h"
      31                 :             : #include "storage/procarray.h"
      32                 :             : #include "storage/sinvaladt.h"
      33                 :             : #include "storage/standby.h"
      34                 :             : #include "utils/hsearch.h"
      35                 :             : #include "utils/injection_point.h"
      36                 :             : #include "utils/ps_status.h"
      37                 :             : #include "utils/timeout.h"
      38                 :             : #include "utils/timestamp.h"
      39                 :             : #include "utils/wait_event.h"
      40                 :             : 
      41                 :             : /* User-settable GUC parameters */
      42                 :             : int         max_standby_archive_delay = 30 * 1000;
      43                 :             : int         max_standby_streaming_delay = 30 * 1000;
      44                 :             : bool        log_recovery_conflict_waits = false;
      45                 :             : 
      46                 :             : /*
      47                 :             :  * Keep track of all the exclusive locks owned by original transactions.
      48                 :             :  * For each known exclusive lock, there is a RecoveryLockEntry in the
      49                 :             :  * RecoveryLockHash hash table.  All RecoveryLockEntrys belonging to a
      50                 :             :  * given XID are chained together so that we can find them easily.
      51                 :             :  * For each original transaction that is known to have any such locks,
      52                 :             :  * there is a RecoveryLockXidEntry in the RecoveryLockXidHash hash table,
      53                 :             :  * which stores the head of the chain of its locks.
      54                 :             :  */
      55                 :             : typedef struct RecoveryLockEntry
      56                 :             : {
      57                 :             :     xl_standby_lock key;        /* hash key: xid, dbOid, relOid */
      58                 :             :     struct RecoveryLockEntry *next; /* chain link */
      59                 :             : } RecoveryLockEntry;
      60                 :             : 
      61                 :             : typedef struct RecoveryLockXidEntry
      62                 :             : {
      63                 :             :     TransactionId xid;          /* hash key -- must be first */
      64                 :             :     struct RecoveryLockEntry *head; /* chain head */
      65                 :             : } RecoveryLockXidEntry;
      66                 :             : 
      67                 :             : static HTAB *RecoveryLockHash = NULL;
      68                 :             : static HTAB *RecoveryLockXidHash = NULL;
      69                 :             : 
      70                 :             : /* Flags set by timeout handlers */
      71                 :             : static volatile sig_atomic_t got_standby_deadlock_timeout = false;
      72                 :             : static volatile sig_atomic_t got_standby_delay_timeout = false;
      73                 :             : static volatile sig_atomic_t got_standby_lock_timeout = false;
      74                 :             : 
      75                 :             : /*
      76                 :             :  * Frequency with which to resend buffer pin conflicts, in case new pinners
      77                 :             :  * snuck in after we did our last broadcast.
      78                 :             :  */
      79                 :             : #define BUFFERPIN_CONFLICT_RESEND_MS    1000
      80                 :             : 
      81                 :             : static void ResolveRecoveryConflictWithVirtualXIDs(VirtualTransactionId *waitlist,
      82                 :             :                                                    RecoveryConflictReason reason,
      83                 :             :                                                    uint32 wait_event_info,
      84                 :             :                                                    bool report_waiting);
      85                 :             : static void SendRecoveryConflictWithBufferPin(RecoveryConflictReason reason);
      86                 :             : static XLogRecPtr LogCurrentRunningXacts(RunningTransactions CurrRunningXacts);
      87                 :             : static void LogAccessExclusiveLocks(int nlocks, xl_standby_lock *locks);
      88                 :             : static const char *get_recovery_conflict_desc(RecoveryConflictReason reason);
      89                 :             : 
      90                 :             : /*
      91                 :             :  * InitRecoveryTransactionEnvironment
      92                 :             :  *      Initialize tracking of our primary's in-progress transactions.
      93                 :             :  *
      94                 :             :  * We need to issue shared invalidations and hold locks. Holding locks
      95                 :             :  * means others may want to wait on us, so we need to make a lock table
      96                 :             :  * vxact entry like a real transaction. We could create and delete
      97                 :             :  * lock table entries for each transaction but its simpler just to create
      98                 :             :  * one permanent entry and leave it there all the time. Locks are then
      99                 :             :  * acquired and released as needed. Yes, this means you can see the
     100                 :             :  * Startup process in pg_locks once we have run this.
     101                 :             :  */
     102                 :             : void
     103                 :         139 : InitRecoveryTransactionEnvironment(void)
     104                 :             : {
     105                 :             :     VirtualTransactionId vxid;
     106                 :             :     HASHCTL     hash_ctl;
     107                 :             : 
     108                 :             :     Assert(RecoveryLockHash == NULL);   /* don't run this twice */
     109                 :             : 
     110                 :             :     /*
     111                 :             :      * Initialize the hash tables for tracking the locks held by each
     112                 :             :      * transaction.
     113                 :             :      */
     114                 :         139 :     hash_ctl.keysize = sizeof(xl_standby_lock);
     115                 :         139 :     hash_ctl.entrysize = sizeof(RecoveryLockEntry);
     116                 :         139 :     RecoveryLockHash = hash_create("RecoveryLockHash",
     117                 :             :                                    64,
     118                 :             :                                    &hash_ctl,
     119                 :             :                                    HASH_ELEM | HASH_BLOBS);
     120                 :         139 :     hash_ctl.keysize = sizeof(TransactionId);
     121                 :         139 :     hash_ctl.entrysize = sizeof(RecoveryLockXidEntry);
     122                 :         139 :     RecoveryLockXidHash = hash_create("RecoveryLockXidHash",
     123                 :             :                                       64,
     124                 :             :                                       &hash_ctl,
     125                 :             :                                       HASH_ELEM | HASH_BLOBS);
     126                 :             : 
     127                 :             :     /*
     128                 :             :      * Initialize shared invalidation management for Startup process, being
     129                 :             :      * careful to register ourselves as a sendOnly process so we don't need to
     130                 :             :      * read messages, nor will we get signaled when the queue starts filling
     131                 :             :      * up.
     132                 :             :      */
     133                 :         139 :     SharedInvalBackendInit(true);
     134                 :             : 
     135                 :             :     /*
     136                 :             :      * Lock a virtual transaction id for Startup process.
     137                 :             :      *
     138                 :             :      * We need to do GetNextLocalTransactionId() because
     139                 :             :      * SharedInvalBackendInit() leaves localTransactionId invalid and the lock
     140                 :             :      * manager doesn't like that at all.
     141                 :             :      *
     142                 :             :      * Note that we don't need to run XactLockTableInsert() because nobody
     143                 :             :      * needs to wait on xids. That sounds a little strange, but table locks
     144                 :             :      * are held by vxids and row level locks are held by xids. All queries
     145                 :             :      * hold AccessShareLocks so never block while we write or lock new rows.
     146                 :             :      */
     147                 :         139 :     MyProc->vxid.procNumber = MyProcNumber;
     148                 :         139 :     vxid.procNumber = MyProcNumber;
     149                 :         139 :     vxid.localTransactionId = GetNextLocalTransactionId();
     150                 :         139 :     VirtualXactLockTableInsert(vxid);
     151                 :             : 
     152                 :         139 :     standbyState = STANDBY_INITIALIZED;
     153                 :         139 : }
     154                 :             : 
     155                 :             : /*
     156                 :             :  * ShutdownRecoveryTransactionEnvironment
     157                 :             :  *      Shut down transaction tracking
     158                 :             :  *
     159                 :             :  * Prepare to switch from hot standby mode to normal operation. Shut down
     160                 :             :  * recovery-time transaction tracking.
     161                 :             :  *
     162                 :             :  * This must be called even in shutdown of startup process if transaction
     163                 :             :  * tracking has been initialized. Otherwise some locks the tracked
     164                 :             :  * transactions were holding will not be released and may interfere with
     165                 :             :  * the processes still running (but will exit soon later) at the exit of
     166                 :             :  * startup process.
     167                 :             :  */
     168                 :             : void
     169                 :         207 : ShutdownRecoveryTransactionEnvironment(void)
     170                 :             : {
     171                 :             :     /*
     172                 :             :      * Do nothing if RecoveryLockHash is NULL because that means that
     173                 :             :      * transaction tracking has not yet been initialized or has already been
     174                 :             :      * shut down.  This makes it safe to have possibly-redundant calls of this
     175                 :             :      * function during process exit.
     176                 :             :      */
     177         [ +  + ]:         207 :     if (RecoveryLockHash == NULL)
     178                 :          68 :         return;
     179                 :             : 
     180                 :             :     /* Mark all tracked in-progress transactions as finished. */
     181                 :         139 :     ExpireAllKnownAssignedTransactionIds();
     182                 :             : 
     183                 :             :     /* Release all locks the tracked transactions were holding */
     184                 :         139 :     StandbyReleaseAllLocks();
     185                 :             : 
     186                 :             :     /* Destroy the lock hash tables. */
     187                 :         139 :     hash_destroy(RecoveryLockHash);
     188                 :         139 :     hash_destroy(RecoveryLockXidHash);
     189                 :         139 :     RecoveryLockHash = NULL;
     190                 :         139 :     RecoveryLockXidHash = NULL;
     191                 :             : 
     192                 :             :     /* Cleanup our VirtualTransaction */
     193                 :         139 :     VirtualXactLockTableCleanup();
     194                 :             : }
     195                 :             : 
     196                 :             : 
     197                 :             : /*
     198                 :             :  * -----------------------------------------------------
     199                 :             :  *      Standby wait timers and backend cancel logic
     200                 :             :  * -----------------------------------------------------
     201                 :             :  */
     202                 :             : 
     203                 :             : /*
     204                 :             :  * Determine the cutoff time at which we want to start canceling conflicting
     205                 :             :  * transactions.  Returns zero (a time safely in the past) if we are willing
     206                 :             :  * to wait forever.
     207                 :             :  */
     208                 :             : static TimestampTz
     209                 :          27 : GetStandbyLimitTime(void)
     210                 :             : {
     211                 :             :     TimestampTz rtime;
     212                 :             :     bool        fromStream;
     213                 :             : 
     214                 :             :     /*
     215                 :             :      * The cutoff time is the last WAL data receipt time plus the appropriate
     216                 :             :      * delay variable.  Delay of -1 means wait forever.
     217                 :             :      */
     218                 :          27 :     GetXLogReceiptTime(&rtime, &fromStream);
     219         [ +  - ]:          27 :     if (fromStream)
     220                 :             :     {
     221         [ -  + ]:          27 :         if (max_standby_streaming_delay < 0)
     222                 :           0 :             return 0;           /* wait forever */
     223                 :          27 :         return TimestampTzPlusMilliseconds(rtime, max_standby_streaming_delay);
     224                 :             :     }
     225                 :             :     else
     226                 :             :     {
     227         [ #  # ]:           0 :         if (max_standby_archive_delay < 0)
     228                 :           0 :             return 0;           /* wait forever */
     229                 :           0 :         return TimestampTzPlusMilliseconds(rtime, max_standby_archive_delay);
     230                 :             :     }
     231                 :             : }
     232                 :             : 
     233                 :             : #define STANDBY_INITIAL_WAIT_US  1000
     234                 :             : static int  standbyWait_us = STANDBY_INITIAL_WAIT_US;
     235                 :             : 
     236                 :             : /*
     237                 :             :  * Standby wait logic for ResolveRecoveryConflictWithVirtualXIDs.
     238                 :             :  * We wait here for a while then return. If we decide we can't wait any
     239                 :             :  * more then we return true, if we can wait some more return false.
     240                 :             :  */
     241                 :             : static bool
     242                 :          15 : WaitExceedsMaxStandbyDelay(uint32 wait_event_info)
     243                 :             : {
     244                 :             :     TimestampTz ltime;
     245                 :             : 
     246         [ -  + ]:          15 :     CHECK_FOR_INTERRUPTS();
     247                 :             : 
     248                 :             :     /* Are we past the limit time? */
     249                 :          15 :     ltime = GetStandbyLimitTime();
     250   [ +  -  +  + ]:          15 :     if (ltime && GetCurrentTimestamp() >= ltime)
     251                 :           3 :         return true;
     252                 :             : 
     253                 :             :     /*
     254                 :             :      * Sleep a bit (this is essential to avoid busy-waiting).
     255                 :             :      */
     256                 :          12 :     pgstat_report_wait_start(wait_event_info);
     257                 :          12 :     pg_usleep(standbyWait_us);
     258                 :          12 :     pgstat_report_wait_end();
     259                 :             : 
     260                 :             :     /*
     261                 :             :      * Progressively increase the sleep times, but not to more than 1s, since
     262                 :             :      * pg_usleep isn't interruptible on some platforms.
     263                 :             :      */
     264                 :          12 :     standbyWait_us *= 2;
     265         [ -  + ]:          12 :     if (standbyWait_us > 1000000)
     266                 :           0 :         standbyWait_us = 1000000;
     267                 :             : 
     268                 :          12 :     return false;
     269                 :             : }
     270                 :             : 
     271                 :             : /*
     272                 :             :  * Log the recovery conflict.
     273                 :             :  *
     274                 :             :  * wait_start is the timestamp when the caller started to wait.
     275                 :             :  * now is the timestamp when this function has been called.
     276                 :             :  * wait_list is the list of virtual transaction ids assigned to
     277                 :             :  * conflicting processes. still_waiting indicates whether
     278                 :             :  * the startup process is still waiting for the recovery conflict
     279                 :             :  * to be resolved or not.
     280                 :             :  */
     281                 :             : void
     282                 :          10 : LogRecoveryConflict(RecoveryConflictReason reason, TimestampTz wait_start,
     283                 :             :                     TimestampTz now, VirtualTransactionId *wait_list,
     284                 :             :                     bool still_waiting)
     285                 :             : {
     286                 :             :     long        secs;
     287                 :             :     int         usecs;
     288                 :             :     long        msecs;
     289                 :             :     StringInfoData buf;
     290                 :          10 :     int         nprocs = 0;
     291                 :             : 
     292                 :             :     /*
     293                 :             :      * There must be no conflicting processes when the recovery conflict has
     294                 :             :      * already been resolved.
     295                 :             :      */
     296                 :             :     Assert(still_waiting || wait_list == NULL);
     297                 :             : 
     298                 :          10 :     TimestampDifference(wait_start, now, &secs, &usecs);
     299                 :          10 :     msecs = secs * 1000 + usecs / 1000;
     300                 :          10 :     usecs = usecs % 1000;
     301                 :             : 
     302         [ +  + ]:          10 :     if (wait_list)
     303                 :             :     {
     304                 :             :         VirtualTransactionId *vxids;
     305                 :             : 
     306                 :             :         /* Construct a string of list of the conflicting processes */
     307                 :           3 :         vxids = wait_list;
     308         [ +  + ]:           6 :         while (VirtualTransactionIdIsValid(*vxids))
     309                 :             :         {
     310                 :           3 :             PGPROC     *proc = ProcNumberGetProc(vxids->procNumber);
     311                 :             : 
     312                 :             :             /* proc can be NULL if the target backend is not active */
     313         [ +  - ]:           3 :             if (proc)
     314                 :             :             {
     315         [ +  - ]:           3 :                 if (nprocs == 0)
     316                 :             :                 {
     317                 :           3 :                     initStringInfo(&buf);
     318                 :           3 :                     appendStringInfo(&buf, "%d", proc->pid);
     319                 :             :                 }
     320                 :             :                 else
     321                 :           0 :                     appendStringInfo(&buf, ", %d", proc->pid);
     322                 :             : 
     323                 :           3 :                 nprocs++;
     324                 :             :             }
     325                 :             : 
     326                 :           3 :             vxids++;
     327                 :             :         }
     328                 :             :     }
     329                 :             : 
     330                 :             :     /*
     331                 :             :      * If wait_list is specified, report the list of PIDs of active
     332                 :             :      * conflicting backends in a detail message. Note that if all the backends
     333                 :             :      * in the list are not active, no detail message is logged.
     334                 :             :      */
     335         [ +  + ]:          10 :     if (still_waiting)
     336                 :             :     {
     337   [ +  -  +  + ]:           5 :         ereport(LOG,
     338                 :             :                 errmsg("recovery still waiting after %ld.%03d ms: %s",
     339                 :             :                        msecs, usecs, get_recovery_conflict_desc(reason)),
     340                 :             :                 nprocs > 0 ? errdetail_log_plural("Conflicting process: %s.",
     341                 :             :                                                   "Conflicting processes: %s.",
     342                 :             :                                                   nprocs, buf.data) : 0);
     343                 :             :     }
     344                 :             :     else
     345                 :             :     {
     346         [ +  - ]:           5 :         ereport(LOG,
     347                 :             :                 errmsg("recovery finished waiting after %ld.%03d ms: %s",
     348                 :             :                        msecs, usecs, get_recovery_conflict_desc(reason)));
     349                 :             :     }
     350                 :             : 
     351         [ +  + ]:          10 :     if (nprocs > 0)
     352                 :           3 :         pfree(buf.data);
     353                 :          10 : }
     354                 :             : 
     355                 :             : /*
     356                 :             :  * This is the main executioner for any query backend that conflicts with
     357                 :             :  * recovery processing. Judgement has already been passed on it within
     358                 :             :  * a specific rmgr. Here we just issue the orders to the procs. The procs
     359                 :             :  * then throw the required error as instructed.
     360                 :             :  *
     361                 :             :  * If report_waiting is true, "waiting" is reported in PS display and the
     362                 :             :  * wait for recovery conflict is reported in the log, if necessary. If
     363                 :             :  * the caller is responsible for reporting them, report_waiting should be
     364                 :             :  * false. Otherwise, both the caller and this function report the same
     365                 :             :  * thing unexpectedly.
     366                 :             :  */
     367                 :             : static void
     368                 :       17124 : ResolveRecoveryConflictWithVirtualXIDs(VirtualTransactionId *waitlist,
     369                 :             :                                        RecoveryConflictReason reason,
     370                 :             :                                        uint32 wait_event_info,
     371                 :             :                                        bool report_waiting)
     372                 :             : {
     373                 :       17124 :     TimestampTz waitStart = 0;
     374                 :       17124 :     bool        waiting = false;
     375                 :       17124 :     bool        logged_recovery_conflict = false;
     376                 :             : 
     377                 :             :     /* Fast exit, to avoid a kernel call if there's no work to be done. */
     378         [ +  + ]:       17124 :     if (!VirtualTransactionIdIsValid(*waitlist))
     379                 :       17121 :         return;
     380                 :             : 
     381                 :             :     /* Set the wait start timestamp for reporting */
     382   [ +  +  -  +  :           3 :     if (report_waiting && (log_recovery_conflict_waits || update_process_title))
                   -  - ]
     383                 :           2 :         waitStart = GetCurrentTimestamp();
     384                 :             : 
     385         [ +  + ]:           6 :     while (VirtualTransactionIdIsValid(*waitlist))
     386                 :             :     {
     387                 :             :         /* reset standbyWait_us for each xact we wait for */
     388                 :           3 :         standbyWait_us = STANDBY_INITIAL_WAIT_US;
     389                 :             : 
     390                 :             :         /* wait until the virtual xid is gone */
     391         [ +  + ]:          18 :         while (!VirtualXactLock(*waitlist, false))
     392                 :             :         {
     393                 :             :             /* Is it time to kill it? */
     394         [ +  + ]:          15 :             if (WaitExceedsMaxStandbyDelay(wait_event_info))
     395                 :             :             {
     396                 :             :                 bool        signaled;
     397                 :             : 
     398                 :             :                 /*
     399                 :             :                  * Now find out who to throw out of the balloon.
     400                 :             :                  */
     401                 :             :                 Assert(VirtualTransactionIdIsValid(*waitlist));
     402                 :           3 :                 signaled = SignalRecoveryConflictWithVirtualXID(*waitlist, reason);
     403                 :             : 
     404                 :             :                 /*
     405                 :             :                  * Wait a little bit for it to die so that we avoid flooding
     406                 :             :                  * an unresponsive backend when system is heavily loaded.
     407                 :             :                  */
     408         [ +  - ]:           3 :                 if (signaled)
     409                 :           3 :                     pg_usleep(5000L);
     410                 :             :             }
     411                 :             : 
     412   [ +  +  +  +  :          15 :             if (waitStart != 0 && (!logged_recovery_conflict || !waiting))
                   +  - ]
     413                 :             :             {
     414                 :          14 :                 TimestampTz now = 0;
     415                 :             :                 bool        maybe_log_conflict;
     416                 :             :                 bool        maybe_update_title;
     417                 :             : 
     418   [ +  -  +  + ]:          14 :                 maybe_log_conflict = (log_recovery_conflict_waits && !logged_recovery_conflict);
     419   [ +  -  +  - ]:          14 :                 maybe_update_title = (update_process_title && !waiting);
     420                 :             : 
     421                 :             :                 /* Get the current timestamp if not report yet */
     422   [ +  +  +  - ]:          14 :                 if (maybe_log_conflict || maybe_update_title)
     423                 :          14 :                     now = GetCurrentTimestamp();
     424                 :             : 
     425                 :             :                 /*
     426                 :             :                  * Report via ps if we have been waiting for more than 500
     427                 :             :                  * msec (should that be configurable?)
     428                 :             :                  */
     429   [ +  -  -  + ]:          28 :                 if (maybe_update_title &&
     430                 :          14 :                     TimestampDifferenceExceeds(waitStart, now, 500))
     431                 :             :                 {
     432                 :           0 :                     set_ps_display_suffix("waiting");
     433                 :           0 :                     waiting = true;
     434                 :             :                 }
     435                 :             : 
     436                 :             :                 /*
     437                 :             :                  * Emit the log message if the startup process is waiting
     438                 :             :                  * longer than deadlock_timeout for recovery conflict.
     439                 :             :                  */
     440   [ +  +  +  + ]:          22 :                 if (maybe_log_conflict &&
     441                 :           8 :                     TimestampDifferenceExceeds(waitStart, now, DeadlockTimeout))
     442                 :             :                 {
     443                 :           2 :                     LogRecoveryConflict(reason, waitStart, now, waitlist, true);
     444                 :           2 :                     logged_recovery_conflict = true;
     445                 :             :                 }
     446                 :             :             }
     447                 :             :         }
     448                 :             : 
     449                 :             :         /* The virtual transaction is gone now, wait for the next one */
     450                 :           3 :         waitlist++;
     451                 :             :     }
     452                 :             : 
     453                 :             :     /*
     454                 :             :      * Emit the log message if recovery conflict was resolved but the startup
     455                 :             :      * process waited longer than deadlock_timeout for it.
     456                 :             :      */
     457         [ +  + ]:           3 :     if (logged_recovery_conflict)
     458                 :           2 :         LogRecoveryConflict(reason, waitStart, GetCurrentTimestamp(),
     459                 :             :                             NULL, false);
     460                 :             : 
     461                 :             :     /* reset ps display to remove the suffix if we added one */
     462         [ -  + ]:           3 :     if (waiting)
     463                 :           0 :         set_ps_display_remove_suffix();
     464                 :             : 
     465                 :             : }
     466                 :             : 
     467                 :             : /*
     468                 :             :  * Generate whatever recovery conflicts are needed to eliminate snapshots that
     469                 :             :  * might see XIDs <= snapshotConflictHorizon as still running.
     470                 :             :  *
     471                 :             :  * snapshotConflictHorizon cutoffs are our standard approach to generating
     472                 :             :  * granular recovery conflicts.  Note that InvalidTransactionId values are
     473                 :             :  * interpreted as "definitely don't need any conflicts" here, which is a
     474                 :             :  * general convention that WAL records can (and often do) depend on.
     475                 :             :  */
     476                 :             : void
     477                 :       17956 : ResolveRecoveryConflictWithSnapshot(TransactionId snapshotConflictHorizon,
     478                 :             :                                     bool isCatalogRel,
     479                 :             :                                     RelFileLocator locator)
     480                 :             : {
     481                 :             :     VirtualTransactionId *backends;
     482                 :             : 
     483                 :             :     /*
     484                 :             :      * If we get passed InvalidTransactionId then we do nothing (no conflict).
     485                 :             :      *
     486                 :             :      * This can happen whenever the changes in the WAL record do not affect
     487                 :             :      * visibility on a standby. For example: a record that only freezes an
     488                 :             :      * xmax from a locker.
     489                 :             :      *
     490                 :             :      * It's also quite common with records generated during index deletion
     491                 :             :      * (original execution of the deletion can reason that a recovery conflict
     492                 :             :      * which is sufficient for the deletion operation must take place before
     493                 :             :      * replay of the deletion record itself).
     494                 :             :      */
     495         [ +  + ]:       17956 :     if (!TransactionIdIsValid(snapshotConflictHorizon))
     496                 :         834 :         return;
     497                 :             : 
     498                 :             :     Assert(TransactionIdIsNormal(snapshotConflictHorizon));
     499                 :       17122 :     backends = GetConflictingVirtualXIDs(snapshotConflictHorizon,
     500                 :             :                                          locator.dbOid);
     501                 :       17122 :     ResolveRecoveryConflictWithVirtualXIDs(backends,
     502                 :             :                                            RECOVERY_CONFLICT_SNAPSHOT,
     503                 :             :                                            WAIT_EVENT_RECOVERY_CONFLICT_SNAPSHOT,
     504                 :             :                                            true);
     505                 :             : 
     506                 :             :     /*
     507                 :             :      * Note that WaitExceedsMaxStandbyDelay() is not taken into account here
     508                 :             :      * (as opposed to ResolveRecoveryConflictWithVirtualXIDs() above). That
     509                 :             :      * seems OK, given that this kind of conflict should not normally be
     510                 :             :      * reached, e.g. due to using a physical replication slot.
     511                 :             :      */
     512   [ +  +  +  + ]:       17122 :     if (IsLogicalDecodingEnabled() && isCatalogRel)
     513                 :          17 :         InvalidateObsoleteReplicationSlots(RS_INVAL_HORIZON, 0, locator.dbOid,
     514                 :             :                                            snapshotConflictHorizon);
     515                 :             : }
     516                 :             : 
     517                 :             : /*
     518                 :             :  * Variant of ResolveRecoveryConflictWithSnapshot that works with
     519                 :             :  * FullTransactionId values
     520                 :             :  */
     521                 :             : void
     522                 :         114 : ResolveRecoveryConflictWithSnapshotFullXid(FullTransactionId snapshotConflictHorizon,
     523                 :             :                                            bool isCatalogRel,
     524                 :             :                                            RelFileLocator locator)
     525                 :             : {
     526                 :             :     /*
     527                 :             :      * ResolveRecoveryConflictWithSnapshot operates on 32-bit TransactionIds,
     528                 :             :      * so truncate the logged FullTransactionId.  If the logged value is very
     529                 :             :      * old, so that XID wrap-around already happened on it, there can't be any
     530                 :             :      * snapshots that still see it.
     531                 :             :      */
     532                 :         114 :     FullTransactionId nextXid = ReadNextFullTransactionId();
     533                 :             :     uint64      diff;
     534                 :             : 
     535                 :         114 :     diff = U64FromFullTransactionId(nextXid) -
     536                 :         114 :         U64FromFullTransactionId(snapshotConflictHorizon);
     537         [ +  - ]:         114 :     if (diff < MaxTransactionId / 2)
     538                 :             :     {
     539                 :             :         TransactionId truncated;
     540                 :             : 
     541                 :         114 :         truncated = XidFromFullTransactionId(snapshotConflictHorizon);
     542                 :         114 :         ResolveRecoveryConflictWithSnapshot(truncated,
     543                 :             :                                             isCatalogRel,
     544                 :             :                                             locator);
     545                 :             :     }
     546                 :         114 : }
     547                 :             : 
     548                 :             : void
     549                 :           1 : ResolveRecoveryConflictWithTablespace(Oid tsid)
     550                 :             : {
     551                 :             :     VirtualTransactionId *temp_file_users;
     552                 :             : 
     553                 :             :     /*
     554                 :             :      * Standby users may be currently using this tablespace for their
     555                 :             :      * temporary files. We only care about current users because
     556                 :             :      * temp_tablespace parameter will just ignore tablespaces that no longer
     557                 :             :      * exist.
     558                 :             :      *
     559                 :             :      * Ask everybody to cancel their queries immediately so we can ensure no
     560                 :             :      * temp files remain and we can remove the tablespace. Nuke the entire
     561                 :             :      * site from orbit, it's the only way to be sure.
     562                 :             :      *
     563                 :             :      * XXX: We could work out the pids of active backends using this
     564                 :             :      * tablespace by examining the temp filenames in the directory. We would
     565                 :             :      * then convert the pids into VirtualXIDs before attempting to cancel
     566                 :             :      * them.
     567                 :             :      *
     568                 :             :      * We don't wait for commit because drop tablespace is non-transactional.
     569                 :             :      */
     570                 :           1 :     temp_file_users = GetConflictingVirtualXIDs(InvalidTransactionId,
     571                 :             :                                                 InvalidOid);
     572                 :           1 :     ResolveRecoveryConflictWithVirtualXIDs(temp_file_users,
     573                 :             :                                            RECOVERY_CONFLICT_TABLESPACE,
     574                 :             :                                            WAIT_EVENT_RECOVERY_CONFLICT_TABLESPACE,
     575                 :             :                                            true);
     576                 :           1 : }
     577                 :             : 
     578                 :             : void
     579                 :          15 : ResolveRecoveryConflictWithDatabase(Oid dbid)
     580                 :             : {
     581                 :             :     /*
     582                 :             :      * We don't do ResolveRecoveryConflictWithVirtualXIDs() here since that
     583                 :             :      * only waits for transactions and completely idle sessions would block
     584                 :             :      * us. This is rare enough that we do this as simply as possible: no wait,
     585                 :             :      * just force them off immediately.
     586                 :             :      *
     587                 :             :      * No locking is required here because we already acquired
     588                 :             :      * AccessExclusiveLock. Anybody trying to connect while we do this will
     589                 :             :      * block during InitPostgres() and then disconnect when they see the
     590                 :             :      * database has been removed.
     591                 :             :      */
     592         [ +  + ]:          17 :     while (CountDBBackends(dbid) > 0)
     593                 :             :     {
     594                 :           2 :         SignalRecoveryConflictWithDatabase(dbid, RECOVERY_CONFLICT_DATABASE);
     595                 :             : 
     596                 :             :         /*
     597                 :             :          * Wait awhile for them to die so that we avoid flooding an
     598                 :             :          * unresponsive backend when system is heavily loaded.
     599                 :             :          */
     600                 :           2 :         pg_usleep(10000);
     601                 :             :     }
     602                 :          15 : }
     603                 :             : 
     604                 :             : /*
     605                 :             :  * ResolveRecoveryConflictWithLock is called from ProcSleep()
     606                 :             :  * to resolve conflicts with other backends holding relation locks.
     607                 :             :  *
     608                 :             :  * The WaitLatch sleep normally done in ProcSleep()
     609                 :             :  * (when not InHotStandby) is performed here, for code clarity.
     610                 :             :  *
     611                 :             :  * We either resolve conflicts immediately or set a timeout to wake us at
     612                 :             :  * the limit of our patience.
     613                 :             :  *
     614                 :             :  * Resolve conflicts by canceling to all backends holding a conflicting
     615                 :             :  * lock.  As we are already queued to be granted the lock, no new lock
     616                 :             :  * requests conflicting with ours will be granted in the meantime.
     617                 :             :  *
     618                 :             :  * We also must check for deadlocks involving the Startup process and
     619                 :             :  * hot-standby backend processes. If deadlock_timeout is reached in
     620                 :             :  * this function, all the backends holding the conflicting locks are
     621                 :             :  * requested to check themselves for deadlocks.
     622                 :             :  *
     623                 :             :  * logging_conflict should be true if the recovery conflict has not been
     624                 :             :  * logged yet even though logging is enabled. After deadlock_timeout is
     625                 :             :  * reached and the request for deadlock check is sent, we wait again to
     626                 :             :  * be signaled by the release of the lock if logging_conflict is false.
     627                 :             :  * Otherwise we return without waiting again so that the caller can report
     628                 :             :  * the recovery conflict. In this case, then, this function is called again
     629                 :             :  * with logging_conflict=false (because the recovery conflict has already
     630                 :             :  * been logged) and we will wait again for the lock to be released.
     631                 :             :  */
     632                 :             : void
     633                 :           4 : ResolveRecoveryConflictWithLock(LOCKTAG locktag, bool logging_conflict)
     634                 :             : {
     635                 :             :     TimestampTz ltime;
     636                 :             :     TimestampTz now;
     637                 :             : 
     638                 :             :     Assert(InHotStandby);
     639                 :             : 
     640                 :           4 :     ltime = GetStandbyLimitTime();
     641                 :           4 :     now = GetCurrentTimestamp();
     642                 :             : 
     643                 :             :     /*
     644                 :             :      * Update waitStart if first time through after the startup process
     645                 :             :      * started waiting for the lock. It should not be updated every time
     646                 :             :      * ResolveRecoveryConflictWithLock() is called during the wait.
     647                 :             :      *
     648                 :             :      * Use the current time obtained for comparison with ltime as waitStart
     649                 :             :      * (i.e., the time when this process started waiting for the lock). Since
     650                 :             :      * getting the current time newly can cause overhead, we reuse the
     651                 :             :      * already-obtained time to avoid that overhead.
     652                 :             :      *
     653                 :             :      * Note that waitStart is updated without holding the lock table's
     654                 :             :      * partition lock, to avoid the overhead by additional lock acquisition.
     655                 :             :      * This can cause "waitstart" in pg_locks to become NULL for a very short
     656                 :             :      * period of time after the wait started even though "granted" is false.
     657                 :             :      * This is OK in practice because we can assume that users are likely to
     658                 :             :      * look at "waitstart" when waiting for the lock for a long time.
     659                 :             :      */
     660         [ +  + ]:           4 :     if (pg_atomic_read_u64(&MyProc->waitStart) == 0)
     661                 :           1 :         pg_atomic_write_u64(&MyProc->waitStart, now);
     662                 :             : 
     663   [ +  +  +  - ]:           4 :     if (now >= ltime && ltime != 0)
     664                 :           1 :     {
     665                 :             :         /*
     666                 :             :          * We're already behind, so clear a path as quickly as possible.
     667                 :             :          */
     668                 :             :         VirtualTransactionId *backends;
     669                 :             : 
     670                 :           1 :         backends = GetLockConflicts(&locktag, AccessExclusiveLock, NULL);
     671                 :             : 
     672                 :             :         /*
     673                 :             :          * Prevent ResolveRecoveryConflictWithVirtualXIDs() from reporting
     674                 :             :          * "waiting" in PS display by disabling its argument report_waiting
     675                 :             :          * because the caller, WaitOnLock(), has already reported that.
     676                 :             :          */
     677                 :           1 :         ResolveRecoveryConflictWithVirtualXIDs(backends,
     678                 :             :                                                RECOVERY_CONFLICT_LOCK,
     679                 :           1 :                                                PG_WAIT_LOCK | locktag.locktag_type,
     680                 :             :                                                false);
     681                 :             :     }
     682                 :             :     else
     683                 :             :     {
     684                 :             :         /*
     685                 :             :          * Wait (or wait again) until ltime, and check for deadlocks as well
     686                 :             :          * if we will be waiting longer than deadlock_timeout
     687                 :             :          */
     688                 :             :         EnableTimeoutParams timeouts[2];
     689                 :           3 :         int         cnt = 0;
     690                 :             : 
     691         [ +  - ]:           3 :         if (ltime != 0)
     692                 :             :         {
     693                 :           3 :             got_standby_lock_timeout = false;
     694                 :           3 :             timeouts[cnt].id = STANDBY_LOCK_TIMEOUT;
     695                 :           3 :             timeouts[cnt].type = TMPARAM_AT;
     696                 :           3 :             timeouts[cnt].fin_time = ltime;
     697                 :           3 :             cnt++;
     698                 :             :         }
     699                 :             : 
     700                 :           3 :         got_standby_deadlock_timeout = false;
     701                 :           3 :         timeouts[cnt].id = STANDBY_DEADLOCK_TIMEOUT;
     702                 :           3 :         timeouts[cnt].type = TMPARAM_AFTER;
     703                 :           3 :         timeouts[cnt].delay_ms = DeadlockTimeout;
     704                 :           3 :         cnt++;
     705                 :             : 
     706                 :           3 :         enable_timeouts(timeouts, cnt);
     707                 :             :     }
     708                 :             : 
     709                 :             :     /* Wait to be signaled by the release of the Relation Lock */
     710                 :           4 :     ProcWaitForSignal(PG_WAIT_LOCK | locktag.locktag_type);
     711                 :             : 
     712                 :             :     /*
     713                 :             :      * Exit if ltime is reached. Then all the backends holding conflicting
     714                 :             :      * locks will be canceled in the next ResolveRecoveryConflictWithLock()
     715                 :             :      * call.
     716                 :             :      */
     717         [ -  + ]:           4 :     if (got_standby_lock_timeout)
     718                 :           0 :         goto cleanup;
     719                 :             : 
     720         [ +  + ]:           4 :     if (got_standby_deadlock_timeout)
     721                 :             :     {
     722                 :             :         VirtualTransactionId *backends;
     723                 :             : 
     724                 :           2 :         backends = GetLockConflicts(&locktag, AccessExclusiveLock, NULL);
     725                 :             : 
     726                 :             :         /* Quick exit if there's no work to be done */
     727         [ -  + ]:           2 :         if (!VirtualTransactionIdIsValid(*backends))
     728                 :           0 :             goto cleanup;
     729                 :             : 
     730                 :             :         /*
     731                 :             :          * Send signals to all the backends holding the conflicting locks, to
     732                 :             :          * ask them to check themselves for deadlocks.
     733                 :             :          */
     734         [ +  + ]:           4 :         while (VirtualTransactionIdIsValid(*backends))
     735                 :             :         {
     736                 :           2 :             (void) SignalRecoveryConflictWithVirtualXID(*backends,
     737                 :             :                                                         RECOVERY_CONFLICT_STARTUP_DEADLOCK);
     738                 :           2 :             backends++;
     739                 :             :         }
     740                 :             : 
     741                 :             :         /*
     742                 :             :          * Exit if the recovery conflict has not been logged yet even though
     743                 :             :          * logging is enabled, so that the caller can log that. Then
     744                 :             :          * RecoveryConflictWithLock() is called again and we will wait again
     745                 :             :          * for the lock to be released.
     746                 :             :          */
     747         [ +  + ]:           2 :         if (logging_conflict)
     748                 :           1 :             goto cleanup;
     749                 :             : 
     750                 :             :         /*
     751                 :             :          * Wait again here to be signaled by the release of the Relation Lock,
     752                 :             :          * to prevent the subsequent RecoveryConflictWithLock() from causing
     753                 :             :          * deadlock_timeout and sending a request for deadlocks check again.
     754                 :             :          * Otherwise the request continues to be sent every deadlock_timeout
     755                 :             :          * until the relation locks are released or ltime is reached.
     756                 :             :          */
     757                 :           1 :         got_standby_deadlock_timeout = false;
     758                 :           1 :         ProcWaitForSignal(PG_WAIT_LOCK | locktag.locktag_type);
     759                 :             :     }
     760                 :             : 
     761                 :           2 : cleanup:
     762                 :             : 
     763                 :             :     /*
     764                 :             :      * Clear any timeout requests established above.  We assume here that the
     765                 :             :      * Startup process doesn't have any other outstanding timeouts than those
     766                 :             :      * used by this function. If that stops being true, we could cancel the
     767                 :             :      * timeouts individually, but that'd be slower.
     768                 :             :      */
     769                 :           4 :     disable_all_timeouts(false);
     770                 :           4 :     got_standby_lock_timeout = false;
     771                 :           4 :     got_standby_deadlock_timeout = false;
     772                 :           4 : }
     773                 :             : 
     774                 :             : /*
     775                 :             :  * ResolveRecoveryConflictWithBufferPin is called from LockBufferForCleanup()
     776                 :             :  * to resolve conflicts with other backends holding buffer pins.
     777                 :             :  *
     778                 :             :  * The ProcWaitForSignal() sleep normally done in LockBufferForCleanup()
     779                 :             :  * (when not InHotStandby) is performed here, for code clarity.
     780                 :             :  *
     781                 :             :  * We either resolve conflicts immediately or set a timeout to wake us at
     782                 :             :  * the limit of our patience (and then again afterwards).
     783                 :             :  *
     784                 :             :  * Resolve conflicts by sending a PROCSIG signal to all backends to check if
     785                 :             :  * they hold one of the buffer pins that is blocking Startup process. If so,
     786                 :             :  * those backends will take an appropriate error action, ERROR or FATAL.
     787                 :             :  *
     788                 :             :  * We also must check for deadlocks.  Deadlocks occur because if queries
     789                 :             :  * wait on a lock, that must be behind an AccessExclusiveLock, which can only
     790                 :             :  * be cleared if the Startup process replays a transaction completion record.
     791                 :             :  * If Startup process is also waiting then that is a deadlock. The deadlock
     792                 :             :  * can occur if the query is waiting and then the Startup sleeps, or if
     793                 :             :  * Startup is sleeping and the query waits on a lock. We protect against
     794                 :             :  * only the former sequence here, the latter sequence is checked prior to
     795                 :             :  * the query sleeping, in CheckRecoveryConflictDeadlock().
     796                 :             :  *
     797                 :             :  * Deadlocks are extremely rare, and relatively expensive to check for,
     798                 :             :  * so we don't do a deadlock check right away ... only if we have had to wait
     799                 :             :  * at least deadlock_timeout.
     800                 :             :  */
     801                 :             : void
     802                 :           8 : ResolveRecoveryConflictWithBufferPin(void)
     803                 :             : {
     804                 :             :     TimestampTz ltime;
     805                 :           8 :     bool        limit_expired = false;
     806                 :             : 
     807                 :             :     Assert(InHotStandby);
     808                 :             : 
     809                 :           8 :     ltime = GetStandbyLimitTime();
     810                 :             : 
     811   [ -  +  -  - ]:           8 :     if (GetCurrentTimestamp() >= ltime && ltime != 0)
     812                 :             :     {
     813                 :             :         /*
     814                 :             :          * We're already behind, so clear a path as quickly as possible.
     815                 :             :          */
     816                 :           0 :         SendRecoveryConflictWithBufferPin(RECOVERY_CONFLICT_BUFFERPIN);
     817                 :           0 :         limit_expired = true;
     818                 :             :     }
     819                 :             :     else
     820                 :             :     {
     821                 :             :         /*
     822                 :             :          * Wake up at ltime, and check for deadlocks as well if we will be
     823                 :             :          * waiting longer than deadlock_timeout
     824                 :             :          */
     825                 :             :         EnableTimeoutParams timeouts[2];
     826                 :           8 :         int         cnt = 0;
     827                 :             : 
     828         [ +  - ]:           8 :         if (ltime != 0)
     829                 :             :         {
     830                 :           8 :             timeouts[cnt].id = STANDBY_TIMEOUT;
     831                 :           8 :             timeouts[cnt].type = TMPARAM_AT;
     832                 :           8 :             timeouts[cnt].fin_time = ltime;
     833                 :           8 :             cnt++;
     834                 :             :         }
     835                 :             : 
     836                 :           8 :         got_standby_deadlock_timeout = false;
     837                 :           8 :         timeouts[cnt].id = STANDBY_DEADLOCK_TIMEOUT;
     838                 :           8 :         timeouts[cnt].type = TMPARAM_AFTER;
     839                 :           8 :         timeouts[cnt].delay_ms = DeadlockTimeout;
     840                 :           8 :         cnt++;
     841                 :             : 
     842                 :           8 :         enable_timeouts(timeouts, cnt);
     843                 :             :     }
     844                 :             : 
     845                 :             :     /*
     846                 :             :      * Wait to be signaled by UnpinBuffer, or for the wait to be interrupted:
     847                 :             :      * either by one of the timeouts established above, or by a self-imposed
     848                 :             :      * latch timeout if the limit already expired.
     849                 :             :      *
     850                 :             :      * (The latter is needed because a backend that pins the buffer after it
     851                 :             :      * has processed our signal would never be told to cancel, and UnpinBuffer
     852                 :             :      * only wakes us when the last other pin goes away.  So wake up
     853                 :             :      * periodically, to let our caller recheck the buffer and come back here
     854                 :             :      * to resend the signal.)
     855                 :             :      *
     856                 :             :      * We assume that only UnpinBuffer() and the timeout requests established
     857                 :             :      * above can wake us up here. WakeupRecovery() called by walreceiver or
     858                 :             :      * SIGHUP signal handler, etc cannot do that because it uses the different
     859                 :             :      * latch from that ProcWaitForSignal() waits on.
     860                 :             :      */
     861         [ -  + ]:           8 :     if (limit_expired)
     862                 :             :     {
     863                 :           0 :         (void) WaitLatch(MyLatch,
     864                 :             :                          WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
     865                 :             :                          BUFFERPIN_CONFLICT_RESEND_MS,
     866                 :             :                          WAIT_EVENT_BUFFER_CLEANUP);
     867                 :           0 :         ResetLatch(MyLatch);
     868         [ #  # ]:           0 :         CHECK_FOR_INTERRUPTS();
     869                 :             :     }
     870                 :             :     else
     871                 :           8 :         ProcWaitForSignal(WAIT_EVENT_BUFFER_CLEANUP);
     872                 :             : 
     873         [ +  + ]:           8 :     if (got_standby_delay_timeout)
     874                 :           1 :         SendRecoveryConflictWithBufferPin(RECOVERY_CONFLICT_BUFFERPIN);
     875         [ +  + ]:           7 :     else if (got_standby_deadlock_timeout)
     876                 :             :     {
     877                 :             :         /*
     878                 :             :          * Send out a request for hot-standby backends to check themselves for
     879                 :             :          * deadlocks.
     880                 :             :          *
     881                 :             :          * XXX The subsequent ResolveRecoveryConflictWithBufferPin() will wait
     882                 :             :          * to be signaled by UnpinBuffer() again and send a request for
     883                 :             :          * deadlocks check if deadlock_timeout happens. This causes the
     884                 :             :          * request to continue to be sent every deadlock_timeout until the
     885                 :             :          * buffer is unpinned or ltime is reached. This would increase the
     886                 :             :          * workload in the startup process and backends. In practice it may
     887                 :             :          * not be so harmful because the period that the buffer is kept pinned
     888                 :             :          * is basically no so long. But we should fix this?
     889                 :             :          */
     890                 :           5 :         SendRecoveryConflictWithBufferPin(RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK);
     891                 :             :     }
     892                 :             : 
     893                 :             :     /*
     894                 :             :      * Clear any timeout requests established above.  We assume here that the
     895                 :             :      * Startup process doesn't have any other timeouts than what this function
     896                 :             :      * uses.  If that stops being true, we could cancel the timeouts
     897                 :             :      * individually, but that'd be slower.
     898                 :             :      */
     899                 :           8 :     disable_all_timeouts(false);
     900                 :           8 :     got_standby_delay_timeout = false;
     901                 :           8 :     got_standby_deadlock_timeout = false;
     902                 :           8 : }
     903                 :             : 
     904                 :             : static void
     905                 :           6 : SendRecoveryConflictWithBufferPin(RecoveryConflictReason reason)
     906                 :             : {
     907                 :             :     Assert(reason == RECOVERY_CONFLICT_BUFFERPIN ||
     908                 :             :            reason == RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK);
     909                 :             : 
     910                 :             :     /*
     911                 :             :      * We send signal to all backends to ask them if they are holding the
     912                 :             :      * buffer pin which is delaying the Startup process. Most of them will be
     913                 :             :      * innocent, but we let the SIGUSR1 handling in each backend decide their
     914                 :             :      * own fate.
     915                 :             :      */
     916                 :           6 :     SignalRecoveryConflictWithDatabase(InvalidOid, reason);
     917                 :           6 : }
     918                 :             : 
     919                 :             : /*
     920                 :             :  * In Hot Standby perform early deadlock detection.  We abort the lock
     921                 :             :  * wait if we are about to sleep while holding the buffer pin that Startup
     922                 :             :  * process is waiting for.
     923                 :             :  *
     924                 :             :  * Note: this code is pessimistic, because there is no way for it to
     925                 :             :  * determine whether an actual deadlock condition is present: the lock we
     926                 :             :  * need to wait for might be unrelated to any held by the Startup process.
     927                 :             :  * Sooner or later, this mechanism should get ripped out in favor of somehow
     928                 :             :  * accounting for buffer locks in DeadLockCheck().  However, errors here
     929                 :             :  * seem to be very low-probability in practice, so for now it's not worth
     930                 :             :  * the trouble.
     931                 :             :  */
     932                 :             : void
     933                 :           1 : CheckRecoveryConflictDeadlock(void)
     934                 :             : {
     935                 :             :     Assert(!InRecovery);        /* do not call in Startup process */
     936                 :             : 
     937         [ +  - ]:           1 :     if (!HoldingBufferPinThatDelaysRecovery())
     938                 :           1 :         return;
     939                 :             : 
     940                 :             :     /*
     941                 :             :      * Error message should match ProcessInterrupts() but we avoid calling
     942                 :             :      * that because we aren't handling an interrupt at this point. Note that
     943                 :             :      * we only cancel the current transaction here, so if we are in a
     944                 :             :      * subtransaction and the pin is held by a parent, then the Startup
     945                 :             :      * process will continue to wait even though we have avoided deadlock.
     946                 :             :      */
     947         [ #  # ]:           0 :     ereport(ERROR,
     948                 :             :             (errcode(ERRCODE_T_R_DEADLOCK_DETECTED),
     949                 :             :              errmsg("canceling statement due to conflict with recovery"),
     950                 :             :              errdetail("User transaction caused buffer deadlock with recovery.")));
     951                 :             : }
     952                 :             : 
     953                 :             : 
     954                 :             : /* --------------------------------
     955                 :             :  *      timeout handler routines
     956                 :             :  * --------------------------------
     957                 :             :  */
     958                 :             : 
     959                 :             : /*
     960                 :             :  * StandbyDeadLockHandler() will be called if STANDBY_DEADLOCK_TIMEOUT is
     961                 :             :  * exceeded.
     962                 :             :  */
     963                 :             : void
     964                 :           7 : StandbyDeadLockHandler(void)
     965                 :             : {
     966                 :           7 :     got_standby_deadlock_timeout = true;
     967                 :           7 : }
     968                 :             : 
     969                 :             : /*
     970                 :             :  * StandbyTimeoutHandler() will be called if STANDBY_TIMEOUT is exceeded.
     971                 :             :  */
     972                 :             : void
     973                 :           1 : StandbyTimeoutHandler(void)
     974                 :             : {
     975                 :           1 :     got_standby_delay_timeout = true;
     976                 :           1 : }
     977                 :             : 
     978                 :             : /*
     979                 :             :  * StandbyLockTimeoutHandler() will be called if STANDBY_LOCK_TIMEOUT is exceeded.
     980                 :             :  */
     981                 :             : void
     982                 :           1 : StandbyLockTimeoutHandler(void)
     983                 :             : {
     984                 :           1 :     got_standby_lock_timeout = true;
     985                 :           1 : }
     986                 :             : 
     987                 :             : /*
     988                 :             :  * -----------------------------------------------------
     989                 :             :  * Locking in Recovery Mode
     990                 :             :  * -----------------------------------------------------
     991                 :             :  *
     992                 :             :  * All locks are held by the Startup process using a single virtual
     993                 :             :  * transaction. This implementation is both simpler and in some senses,
     994                 :             :  * more correct. The locks held mean "some original transaction held
     995                 :             :  * this lock, so query access is not allowed at this time". So the Startup
     996                 :             :  * process is the proxy by which the original locks are implemented.
     997                 :             :  *
     998                 :             :  * We only keep track of AccessExclusiveLocks, which are only ever held by
     999                 :             :  * one transaction on one relation.
    1000                 :             :  *
    1001                 :             :  * We keep a table of known locks in the RecoveryLockHash hash table.
    1002                 :             :  * The point of that table is to let us efficiently de-duplicate locks,
    1003                 :             :  * which is important because checkpoints will re-report the same locks
    1004                 :             :  * already held.  There is also a RecoveryLockXidHash table with one entry
    1005                 :             :  * per xid, which allows us to efficiently find all the locks held by a
    1006                 :             :  * given original transaction.
    1007                 :             :  *
    1008                 :             :  * We use session locks rather than normal locks so we don't need
    1009                 :             :  * ResourceOwners.
    1010                 :             :  */
    1011                 :             : 
    1012                 :             : 
    1013                 :             : void
    1014                 :       29613 : StandbyAcquireAccessExclusiveLock(TransactionId xid, Oid dbOid, Oid relOid)
    1015                 :             : {
    1016                 :             :     RecoveryLockXidEntry *xidentry;
    1017                 :             :     RecoveryLockEntry *lockentry;
    1018                 :             :     xl_standby_lock key;
    1019                 :             :     LOCKTAG     locktag;
    1020                 :             :     bool        found;
    1021                 :             : 
    1022                 :             :     /* Already processed? */
    1023   [ +  -  +  + ]:       59226 :     if (!TransactionIdIsValid(xid) ||
    1024         [ -  + ]:       59207 :         TransactionIdDidCommit(xid) ||
    1025                 :       29594 :         TransactionIdDidAbort(xid))
    1026                 :          19 :         return;
    1027                 :             : 
    1028         [ -  + ]:       29594 :     elog(DEBUG4, "adding recovery lock: db %u rel %u", dbOid, relOid);
    1029                 :             : 
    1030                 :             :     /* dbOid is InvalidOid when we are locking a shared relation. */
    1031                 :             :     Assert(OidIsValid(relOid));
    1032                 :             : 
    1033                 :             :     /* Create a hash entry for this xid, if we don't have one already. */
    1034                 :       29594 :     xidentry = hash_search(RecoveryLockXidHash, &xid, HASH_ENTER, &found);
    1035         [ +  + ]:       29594 :     if (!found)
    1036                 :             :     {
    1037                 :             :         Assert(xidentry->xid == xid);    /* dynahash should have set this */
    1038                 :       12162 :         xidentry->head = NULL;
    1039                 :             :     }
    1040                 :             : 
    1041                 :             :     /* Create a hash entry for this lock, unless we have one already. */
    1042                 :       29594 :     key.xid = xid;
    1043                 :       29594 :     key.dbOid = dbOid;
    1044                 :       29594 :     key.relOid = relOid;
    1045                 :       29594 :     lockentry = hash_search(RecoveryLockHash, &key, HASH_ENTER, &found);
    1046         [ +  + ]:       29594 :     if (!found)
    1047                 :             :     {
    1048                 :             :         /* First, acquire the lock ... */
    1049                 :       28300 :         SET_LOCKTAG_RELATION(locktag, dbOid, relOid);
    1050                 :             : 
    1051                 :       28300 :         (void) LockAcquire(&locktag, AccessExclusiveLock, true, false);
    1052                 :             : 
    1053                 :             :         /* ... and then, as it is new, link it into the XID's list. */
    1054                 :       28300 :         lockentry->next = xidentry->head;
    1055                 :       28300 :         xidentry->head = lockentry;
    1056                 :             :     }
    1057                 :             : }
    1058                 :             : 
    1059                 :             : /*
    1060                 :             :  * Release all the locks associated with this RecoveryLockXidEntry.
    1061                 :             :  */
    1062                 :             : static void
    1063                 :       12162 : StandbyReleaseXidEntryLocks(RecoveryLockXidEntry *xidentry)
    1064                 :             : {
    1065                 :             :     RecoveryLockEntry *entry;
    1066                 :             :     RecoveryLockEntry *next;
    1067                 :             : 
    1068         [ +  + ]:       40462 :     for (entry = xidentry->head; entry != NULL; entry = next)
    1069                 :             :     {
    1070                 :             :         LOCKTAG     locktag;
    1071                 :             : 
    1072         [ -  + ]:       28300 :         elog(DEBUG4,
    1073                 :             :              "releasing recovery lock: xid %u db %u rel %u",
    1074                 :             :              entry->key.xid, entry->key.dbOid, entry->key.relOid);
    1075                 :             :         /* Release the lock ... */
    1076                 :       28300 :         SET_LOCKTAG_RELATION(locktag, entry->key.dbOid, entry->key.relOid);
    1077         [ -  + ]:       28300 :         if (!LockRelease(&locktag, AccessExclusiveLock, true))
    1078                 :             :         {
    1079         [ #  # ]:           0 :             elog(LOG,
    1080                 :             :                  "RecoveryLockHash contains entry for lock no longer recorded by lock manager: xid %u database %u relation %u",
    1081                 :             :                  entry->key.xid, entry->key.dbOid, entry->key.relOid);
    1082                 :             :             Assert(false);
    1083                 :             :         }
    1084                 :             :         /* ... and remove the per-lock hash entry */
    1085                 :       28300 :         next = entry->next;
    1086                 :       28300 :         hash_search(RecoveryLockHash, entry, HASH_REMOVE, NULL);
    1087                 :             :     }
    1088                 :             : 
    1089                 :       12162 :     xidentry->head = NULL;       /* just for paranoia */
    1090                 :       12162 : }
    1091                 :             : 
    1092                 :             : /*
    1093                 :             :  * Release locks for specific XID, or all locks if it's InvalidXid.
    1094                 :             :  */
    1095                 :             : static void
    1096                 :       12854 : StandbyReleaseLocks(TransactionId xid)
    1097                 :             : {
    1098                 :             :     RecoveryLockXidEntry *entry;
    1099                 :             : 
    1100         [ +  - ]:       12854 :     if (TransactionIdIsValid(xid))
    1101                 :             :     {
    1102         [ +  + ]:       12854 :         if ((entry = hash_search(RecoveryLockXidHash, &xid, HASH_FIND, NULL)))
    1103                 :             :         {
    1104                 :       12161 :             StandbyReleaseXidEntryLocks(entry);
    1105                 :       12161 :             hash_search(RecoveryLockXidHash, entry, HASH_REMOVE, NULL);
    1106                 :             :         }
    1107                 :             :     }
    1108                 :             :     else
    1109                 :           0 :         StandbyReleaseAllLocks();
    1110                 :       12854 : }
    1111                 :             : 
    1112                 :             : /*
    1113                 :             :  * Release locks for a transaction tree, starting at xid down, from
    1114                 :             :  * RecoveryLockXidHash.
    1115                 :             :  *
    1116                 :             :  * Called during WAL replay of COMMIT/ROLLBACK when in hot standby mode,
    1117                 :             :  * to remove any AccessExclusiveLocks requested by a transaction.
    1118                 :             :  */
    1119                 :             : void
    1120                 :       12353 : StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
    1121                 :             : {
    1122                 :             :     int         i;
    1123                 :             : 
    1124                 :       12353 :     StandbyReleaseLocks(xid);
    1125                 :             : 
    1126         [ +  + ]:       12854 :     for (i = 0; i < nsubxids; i++)
    1127                 :         501 :         StandbyReleaseLocks(subxids[i]);
    1128                 :       12353 : }
    1129                 :             : 
    1130                 :             : /*
    1131                 :             :  * Called at end of recovery and when we see a shutdown checkpoint.
    1132                 :             :  */
    1133                 :             : void
    1134                 :         139 : StandbyReleaseAllLocks(void)
    1135                 :             : {
    1136                 :             :     HASH_SEQ_STATUS status;
    1137                 :             :     RecoveryLockXidEntry *entry;
    1138                 :             : 
    1139         [ +  + ]:         139 :     elog(DEBUG2, "release all standby locks");
    1140                 :             : 
    1141                 :         139 :     hash_seq_init(&status, RecoveryLockXidHash);
    1142         [ +  + ]:         140 :     while ((entry = hash_seq_search(&status)))
    1143                 :             :     {
    1144                 :           1 :         StandbyReleaseXidEntryLocks(entry);
    1145                 :           1 :         hash_search(RecoveryLockXidHash, entry, HASH_REMOVE, NULL);
    1146                 :             :     }
    1147                 :         139 : }
    1148                 :             : 
    1149                 :             : /*
    1150                 :             :  * StandbyReleaseOldLocks
    1151                 :             :  *      Release standby locks held by top-level XIDs that aren't running,
    1152                 :             :  *      as long as they're not prepared transactions.
    1153                 :             :  *
    1154                 :             :  * This is needed to prune the locks of crashed transactions, which didn't
    1155                 :             :  * write an ABORT/COMMIT record.
    1156                 :             :  */
    1157                 :             : void
    1158                 :         920 : StandbyReleaseOldLocks(TransactionId oldxid)
    1159                 :             : {
    1160                 :             :     HASH_SEQ_STATUS status;
    1161                 :             :     RecoveryLockXidEntry *entry;
    1162                 :             : 
    1163                 :         920 :     hash_seq_init(&status, RecoveryLockXidHash);
    1164         [ +  + ]:        1206 :     while ((entry = hash_seq_search(&status)))
    1165                 :             :     {
    1166                 :             :         Assert(TransactionIdIsValid(entry->xid));
    1167                 :             : 
    1168                 :             :         /* Skip if prepared transaction. */
    1169         [ -  + ]:         286 :         if (StandbyTransactionIdIsPrepared(entry->xid))
    1170                 :           0 :             continue;
    1171                 :             : 
    1172                 :             :         /* Skip if >= oldxid. */
    1173         [ +  - ]:         286 :         if (!TransactionIdPrecedes(entry->xid, oldxid))
    1174                 :         286 :             continue;
    1175                 :             : 
    1176                 :             :         /* Remove all locks and hash table entry. */
    1177                 :           0 :         StandbyReleaseXidEntryLocks(entry);
    1178                 :           0 :         hash_search(RecoveryLockXidHash, entry, HASH_REMOVE, NULL);
    1179                 :             :     }
    1180                 :         920 : }
    1181                 :             : 
    1182                 :             : /*
    1183                 :             :  * --------------------------------------------------------------------
    1184                 :             :  *      Recovery handling for Rmgr RM_STANDBY_ID
    1185                 :             :  *
    1186                 :             :  * These record types will only be created if XLogStandbyInfoActive()
    1187                 :             :  * --------------------------------------------------------------------
    1188                 :             :  */
    1189                 :             : 
    1190                 :             : void
    1191                 :       30133 : standby_redo(XLogReaderState *record)
    1192                 :             : {
    1193                 :       30133 :     uint8       info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
    1194                 :             : 
    1195                 :             :     /* Backup blocks are not used in standby records */
    1196                 :             :     Assert(!XLogRecHasAnyBlockRefs(record));
    1197                 :             : 
    1198                 :             :     /* Do nothing if we're not in hot standby mode */
    1199         [ +  + ]:       30133 :     if (standbyState == STANDBY_DISABLED)
    1200                 :         168 :         return;
    1201                 :             : 
    1202         [ +  + ]:       29965 :     if (info == XLOG_STANDBY_LOCK)
    1203                 :             :     {
    1204                 :       28469 :         xl_standby_locks *xlrec = (xl_standby_locks *) XLogRecGetData(record);
    1205                 :             :         int         i;
    1206                 :             : 
    1207         [ +  + ]:       58082 :         for (i = 0; i < xlrec->nlocks; i++)
    1208                 :       29613 :             StandbyAcquireAccessExclusiveLock(xlrec->locks[i].xid,
    1209                 :             :                                               xlrec->locks[i].dbOid,
    1210                 :             :                                               xlrec->locks[i].relOid);
    1211                 :             :     }
    1212         [ +  + ]:        1496 :     else if (info == XLOG_RUNNING_XACTS)
    1213                 :             :     {
    1214                 :         841 :         xl_running_xacts *xlrec = (xl_running_xacts *) XLogRecGetData(record);
    1215                 :             :         RunningTransactionsData running;
    1216                 :             : 
    1217                 :         841 :         running.xcnt = xlrec->xcnt;
    1218                 :         841 :         running.subxcnt = xlrec->subxcnt;
    1219                 :         841 :         running.subxid_status = xlrec->subxid_overflow ? SUBXIDS_MISSING : SUBXIDS_IN_ARRAY;
    1220                 :         841 :         running.nextXid = xlrec->nextXid;
    1221                 :         841 :         running.latestCompletedXid = xlrec->latestCompletedXid;
    1222                 :         841 :         running.oldestRunningXid = xlrec->oldestRunningXid;
    1223                 :         841 :         running.xids = xlrec->xids;
    1224                 :             : 
    1225                 :         841 :         ProcArrayApplyRecoveryInfo(&running);
    1226                 :             : 
    1227                 :             :         /*
    1228                 :             :          * The startup process currently has no convenient way to schedule
    1229                 :             :          * stats to be reported. XLOG_RUNNING_XACTS records issued at a
    1230                 :             :          * regular cadence, making this a convenient location to report stats.
    1231                 :             :          * While these records aren't generated with wal_level=minimal, stats
    1232                 :             :          * also cannot be accessed during WAL replay.
    1233                 :             :          */
    1234                 :         841 :         pgstat_report_stat(true);
    1235                 :             :     }
    1236         [ +  - ]:         655 :     else if (info == XLOG_INVALIDATIONS)
    1237                 :             :     {
    1238                 :         655 :         xl_invalidations *xlrec = (xl_invalidations *) XLogRecGetData(record);
    1239                 :             : 
    1240                 :         655 :         ProcessCommittedInvalidationMessages(xlrec->msgs,
    1241                 :             :                                              xlrec->nmsgs,
    1242                 :         655 :                                              xlrec->relcacheInitFileInval,
    1243                 :             :                                              xlrec->dbId,
    1244                 :             :                                              xlrec->tsId);
    1245                 :             :     }
    1246                 :             :     else
    1247         [ #  # ]:           0 :         elog(PANIC, "standby_redo: unknown op code %u", info);
    1248                 :             : }
    1249                 :             : 
    1250                 :             : /*
    1251                 :             :  * Log details of the current snapshot to WAL. This allows the snapshot state
    1252                 :             :  * to be reconstructed on the standby and for logical decoding.
    1253                 :             :  *
    1254                 :             :  * This is used for Hot Standby as follows:
    1255                 :             :  *
    1256                 :             :  * We can move directly to STANDBY_SNAPSHOT_READY at startup if we
    1257                 :             :  * start from a shutdown checkpoint because we know nothing was running
    1258                 :             :  * at that time and our recovery snapshot is known empty. In the more
    1259                 :             :  * typical case of an online checkpoint we need to jump through a few
    1260                 :             :  * hoops to get a correct recovery snapshot and this requires a two or
    1261                 :             :  * sometimes a three stage process.
    1262                 :             :  *
    1263                 :             :  * The initial snapshot must contain all running xids and all current
    1264                 :             :  * AccessExclusiveLocks at a point in time on the standby. Assembling
    1265                 :             :  * that information while the server is running requires many and
    1266                 :             :  * various LWLocks, so we choose to derive that information piece by
    1267                 :             :  * piece and then re-assemble that info on the standby. When that
    1268                 :             :  * information is fully assembled we move to STANDBY_SNAPSHOT_READY.
    1269                 :             :  *
    1270                 :             :  * Since locking on the primary when we derive the information is not
    1271                 :             :  * strict, we note that there is a time window between the derivation and
    1272                 :             :  * writing to WAL of the derived information. That allows race conditions
    1273                 :             :  * that we must resolve, since xids and locks may enter or leave the
    1274                 :             :  * snapshot during that window. This creates the issue that an xid or
    1275                 :             :  * lock may start *after* the snapshot has been derived yet *before* the
    1276                 :             :  * snapshot is logged in the running xacts WAL record. We resolve this by
    1277                 :             :  * starting to accumulate changes at a point just prior to when we derive
    1278                 :             :  * the snapshot on the primary, then ignore duplicates when we later apply
    1279                 :             :  * the snapshot from the running xacts record. This is implemented during
    1280                 :             :  * CreateCheckPoint() where we use the logical checkpoint location as
    1281                 :             :  * our starting point and then write the running xacts record immediately
    1282                 :             :  * before writing the main checkpoint WAL record. Since we always start
    1283                 :             :  * up from a checkpoint and are immediately at our starting point, we
    1284                 :             :  * unconditionally move to STANDBY_INITIALIZED. After this point we
    1285                 :             :  * must do 4 things:
    1286                 :             :  *  * move shared nextXid forwards as we see new xids
    1287                 :             :  *  * extend the clog and subtrans with each new xid
    1288                 :             :  *  * keep track of uncommitted known assigned xids
    1289                 :             :  *  * keep track of uncommitted AccessExclusiveLocks
    1290                 :             :  *
    1291                 :             :  * When we see a commit/abort we must remove known assigned xids and locks
    1292                 :             :  * from the completing transaction. Attempted removals that cannot locate
    1293                 :             :  * an entry are expected and must not cause an error when we are in state
    1294                 :             :  * STANDBY_INITIALIZED. This is implemented in StandbyReleaseLocks() and
    1295                 :             :  * KnownAssignedXidsRemove().
    1296                 :             :  *
    1297                 :             :  * Later, when we apply the running xact data we must be careful to ignore
    1298                 :             :  * transactions already committed, since those commits raced ahead when
    1299                 :             :  * making WAL entries.
    1300                 :             :  *
    1301                 :             :  * For logical decoding only the running xacts information is needed;
    1302                 :             :  * there's no need to look at the locking information, but it's logged anyway,
    1303                 :             :  * as there's no independent knob to just enable logical decoding. For
    1304                 :             :  * details of how this is used, check snapbuild.c's introductory comment.
    1305                 :             :  *
    1306                 :             :  *
    1307                 :             :  * Returns the RecPtr of the last inserted record.
    1308                 :             :  */
    1309                 :             : XLogRecPtr
    1310                 :        1638 : LogStandbySnapshot(void)
    1311                 :             : {
    1312                 :             :     XLogRecPtr  recptr;
    1313                 :             :     RunningTransactions running;
    1314                 :             :     xl_standby_lock *locks;
    1315                 :             :     int         nlocks;
    1316                 :             :     bool        xlog_logical_info;
    1317                 :             : 
    1318                 :             :     Assert(XLogStandbyInfoActive());
    1319                 :             : 
    1320                 :             : #ifdef USE_INJECTION_POINTS
    1321         [ +  + ]:        1638 :     if (IS_INJECTION_POINT_ATTACHED("skip-log-running-xacts"))
    1322                 :             :     {
    1323                 :             :         /*
    1324                 :             :          * This record could move slot's xmin forward during decoding, leading
    1325                 :             :          * to unpredictable results, so skip it when requested by the test.
    1326                 :             :          */
    1327                 :           1 :         return GetInsertRecPtr();
    1328                 :             :     }
    1329                 :             : #endif
    1330                 :             : 
    1331                 :             :     /*
    1332                 :             :      * Decide whether to hold ProcArrayLock until the xl_running_xacts record
    1333                 :             :      * is inserted (see below). We check the shared xlog_logical_info flag
    1334                 :             :      * rather than whether logical decoding is enabled: the activation sets
    1335                 :             :      * the flag and waits for all processes to absorb the barrier before it
    1336                 :             :      * marks logical decoding as enabled, so a process that has already
    1337                 :             :      * absorbed the barrier would otherwise not hold the lock while the
    1338                 :             :      * activation completes. The process-local cache doesn't work either, as
    1339                 :             :      * its update is deferred until the end of the transaction if we have an
    1340                 :             :      * XID.
    1341                 :             :      *
    1342                 :             :      * If the flag is off here, a concurrent activation cannot complete until
    1343                 :             :      * we absorb the barrier, which we don't do before inserting the record
    1344                 :             :      * since nothing below processes interrupts.
    1345                 :             :      *
    1346                 :             :      * This must be checked before acquiring ProcArrayLock, because taking
    1347                 :             :      * LogicalDecodingControlLock while holding ProcArrayLock could deadlock
    1348                 :             :      * with DisableLogicalDecoding() and CreateInitDecodingContext().
    1349                 :             :      */
    1350                 :        1637 :     xlog_logical_info = IsXLogLogicalInfoEnabled();
    1351                 :             : 
    1352                 :             :     /*
    1353                 :             :      * Tests stop here to let a concurrent activation complete. Note that a
    1354                 :             :      * process waiting here can absorb the barrier, unlike in the code below.
    1355                 :             :      */
    1356                 :        1637 :     INJECTION_POINT("log-standby-snapshot", NULL);
    1357                 :             : 
    1358                 :             :     /*
    1359                 :             :      * Get details of any AccessExclusiveLocks being held at the moment.
    1360                 :             :      */
    1361                 :        1637 :     locks = GetRunningTransactionLocks(&nlocks);
    1362         [ +  + ]:        1637 :     if (nlocks > 0)
    1363                 :         164 :         LogAccessExclusiveLocks(nlocks, locks);
    1364                 :        1637 :     pfree(locks);
    1365                 :             : 
    1366                 :             :     /*
    1367                 :             :      * Log details of all in-progress transactions. This should be the last
    1368                 :             :      * record we write, because standby will open up when it sees this.
    1369                 :             :      */
    1370                 :        1637 :     running = GetRunningTransactionData();
    1371                 :             : 
    1372                 :             :     /*
    1373                 :             :      * GetRunningTransactionData() acquired ProcArrayLock, we must release it.
    1374                 :             :      * For Hot Standby this can be done before inserting the WAL record
    1375                 :             :      * because ProcArrayApplyRecoveryInfo() rechecks the commit status using
    1376                 :             :      * the clog. For logical decoding, though, the lock can't be released
    1377                 :             :      * early because the clog might be "in the future" from the POV of the
    1378                 :             :      * historic snapshot. This would allow for situations where we're waiting
    1379                 :             :      * for the end of a transaction listed in the xl_running_xacts record
    1380                 :             :      * which, according to the WAL, has committed before the xl_running_xacts
    1381                 :             :      * record. Fortunately this routine isn't executed frequently, and it's
    1382                 :             :      * only a shared lock.
    1383                 :             :      */
    1384         [ +  + ]:        1637 :     if (!xlog_logical_info)
    1385                 :        1002 :         LWLockRelease(ProcArrayLock);
    1386                 :             : 
    1387                 :        1637 :     recptr = LogCurrentRunningXacts(running);
    1388                 :             : 
    1389                 :             :     /* Release lock if we kept it longer ... */
    1390         [ +  + ]:        1637 :     if (xlog_logical_info)
    1391                 :         635 :         LWLockRelease(ProcArrayLock);
    1392                 :             : 
    1393                 :             :     /* GetRunningTransactionData() acquired XidGenLock, we must release it */
    1394                 :        1637 :     LWLockRelease(XidGenLock);
    1395                 :             : 
    1396                 :             :     /*
    1397                 :             :      * If xlog_logical_info was false, logical decoding cannot have been
    1398                 :             :      * enabled since we checked it, as we haven't processed interrupts since
    1399                 :             :      * then. This must be checked after releasing XidGenLock to avoid
    1400                 :             :      * deadlocks.
    1401                 :             :      */
    1402                 :             :     Assert(xlog_logical_info || !IsLogicalDecodingEnabled());
    1403                 :             : 
    1404                 :        1637 :     return recptr;
    1405                 :             : }
    1406                 :             : 
    1407                 :             : /*
    1408                 :             :  * Record an enhanced snapshot of running transactions into WAL.
    1409                 :             :  *
    1410                 :             :  * The definitions of RunningTransactionsData and xl_running_xacts are
    1411                 :             :  * similar. We keep them separate because xl_running_xacts is a contiguous
    1412                 :             :  * chunk of memory and never exists fully until it is assembled in WAL.
    1413                 :             :  * The inserted records are marked as not being important for durability,
    1414                 :             :  * to avoid triggering superfluous checkpoint / archiving activity.
    1415                 :             :  */
    1416                 :             : static XLogRecPtr
    1417                 :        1637 : LogCurrentRunningXacts(RunningTransactions CurrRunningXacts)
    1418                 :             : {
    1419                 :             :     xl_running_xacts xlrec;
    1420                 :             :     XLogRecPtr  recptr;
    1421                 :             : 
    1422                 :        1637 :     xlrec.xcnt = CurrRunningXacts->xcnt;
    1423                 :        1637 :     xlrec.subxcnt = CurrRunningXacts->subxcnt;
    1424                 :        1637 :     xlrec.subxid_overflow = (CurrRunningXacts->subxid_status != SUBXIDS_IN_ARRAY);
    1425                 :        1637 :     xlrec.nextXid = CurrRunningXacts->nextXid;
    1426                 :        1637 :     xlrec.oldestRunningXid = CurrRunningXacts->oldestRunningXid;
    1427                 :        1637 :     xlrec.latestCompletedXid = CurrRunningXacts->latestCompletedXid;
    1428                 :             : 
    1429                 :             :     /* Header */
    1430                 :        1637 :     XLogBeginInsert();
    1431                 :        1637 :     XLogSetRecordFlags(XLOG_MARK_UNIMPORTANT);
    1432                 :        1637 :     XLogRegisterData(&xlrec, MinSizeOfXactRunningXacts);
    1433                 :             : 
    1434                 :             :     /* array of TransactionIds */
    1435         [ +  + ]:        1637 :     if (xlrec.xcnt > 0)
    1436                 :         524 :         XLogRegisterData(CurrRunningXacts->xids,
    1437                 :         524 :                          (xlrec.xcnt + xlrec.subxcnt) * sizeof(TransactionId));
    1438                 :             : 
    1439                 :        1637 :     recptr = XLogInsert(RM_STANDBY_ID, XLOG_RUNNING_XACTS);
    1440                 :             : 
    1441         [ +  + ]:        1637 :     if (xlrec.subxid_overflow)
    1442         [ -  + ]:           1 :         elog(DEBUG2,
    1443                 :             :              "snapshot of %d running transactions overflowed (lsn %X/%08X oldest xid %u latest complete %u next xid %u)",
    1444                 :             :              CurrRunningXacts->xcnt,
    1445                 :             :              LSN_FORMAT_ARGS(recptr),
    1446                 :             :              CurrRunningXacts->oldestRunningXid,
    1447                 :             :              CurrRunningXacts->latestCompletedXid,
    1448                 :             :              CurrRunningXacts->nextXid);
    1449                 :             :     else
    1450         [ +  + ]:        1636 :         elog(DEBUG2,
    1451                 :             :              "snapshot of %d+%d running transaction ids (lsn %X/%08X oldest xid %u latest complete %u next xid %u)",
    1452                 :             :              CurrRunningXacts->xcnt, CurrRunningXacts->subxcnt,
    1453                 :             :              LSN_FORMAT_ARGS(recptr),
    1454                 :             :              CurrRunningXacts->oldestRunningXid,
    1455                 :             :              CurrRunningXacts->latestCompletedXid,
    1456                 :             :              CurrRunningXacts->nextXid);
    1457                 :             : 
    1458                 :             :     /*
    1459                 :             :      * Ensure running_xacts information is synced to disk not too far in the
    1460                 :             :      * future. We don't want to stall anything though (i.e. use XLogFlush()),
    1461                 :             :      * so we let the wal writer do it during normal operation.
    1462                 :             :      * XLogSetAsyncXactLSN() conveniently will mark the LSN as to-be-synced
    1463                 :             :      * and nudge the WALWriter into action if sleeping. Check
    1464                 :             :      * XLogBackgroundFlush() for details why a record might not be flushed
    1465                 :             :      * without it.
    1466                 :             :      */
    1467                 :        1637 :     XLogSetAsyncXactLSN(recptr);
    1468                 :             : 
    1469                 :        1637 :     return recptr;
    1470                 :             : }
    1471                 :             : 
    1472                 :             : /*
    1473                 :             :  * Wholesale logging of AccessExclusiveLocks. Other lock types need not be
    1474                 :             :  * logged, as described in backend/storage/lmgr/README.
    1475                 :             :  */
    1476                 :             : static void
    1477                 :      175663 : LogAccessExclusiveLocks(int nlocks, xl_standby_lock *locks)
    1478                 :             : {
    1479                 :             :     xl_standby_locks xlrec;
    1480                 :             : 
    1481                 :      175663 :     xlrec.nlocks = nlocks;
    1482                 :             : 
    1483                 :      175663 :     XLogBeginInsert();
    1484                 :      175663 :     XLogRegisterData(&xlrec, offsetof(xl_standby_locks, locks));
    1485                 :      175663 :     XLogRegisterData(locks, nlocks * sizeof(xl_standby_lock));
    1486                 :      175663 :     XLogSetRecordFlags(XLOG_MARK_UNIMPORTANT);
    1487                 :             : 
    1488                 :      175663 :     (void) XLogInsert(RM_STANDBY_ID, XLOG_STANDBY_LOCK);
    1489                 :      175663 : }
    1490                 :             : 
    1491                 :             : /*
    1492                 :             :  * Individual logging of AccessExclusiveLocks for use during LockAcquire()
    1493                 :             :  */
    1494                 :             : void
    1495                 :      175499 : LogAccessExclusiveLock(Oid dbOid, Oid relOid)
    1496                 :             : {
    1497                 :             :     xl_standby_lock xlrec;
    1498                 :             : 
    1499                 :      175499 :     xlrec.xid = GetCurrentTransactionId();
    1500                 :             : 
    1501                 :      175499 :     xlrec.dbOid = dbOid;
    1502                 :      175499 :     xlrec.relOid = relOid;
    1503                 :             : 
    1504                 :      175499 :     LogAccessExclusiveLocks(1, &xlrec);
    1505                 :      175499 :     MyXactFlags |= XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK;
    1506                 :      175499 : }
    1507                 :             : 
    1508                 :             : /*
    1509                 :             :  * Prepare to log an AccessExclusiveLock, for use during LockAcquire()
    1510                 :             :  */
    1511                 :             : void
    1512                 :      175713 : LogAccessExclusiveLockPrepare(void)
    1513                 :             : {
    1514                 :             :     /*
    1515                 :             :      * Ensure that a TransactionId has been assigned to this transaction, for
    1516                 :             :      * two reasons, both related to lock release on the standby. First, we
    1517                 :             :      * must assign an xid so that RecordTransactionCommit() and
    1518                 :             :      * RecordTransactionAbort() do not optimise away the transaction
    1519                 :             :      * completion record which recovery relies upon to release locks. It's a
    1520                 :             :      * hack, but for a corner case not worth adding code for into the main
    1521                 :             :      * commit path. Second, we must assign an xid before the lock is recorded
    1522                 :             :      * in shared memory, otherwise a concurrently executing
    1523                 :             :      * GetRunningTransactionLocks() might see a lock associated with an
    1524                 :             :      * InvalidTransactionId which we later assert cannot happen.
    1525                 :             :      */
    1526                 :      175713 :     (void) GetCurrentTransactionId();
    1527                 :      175713 : }
    1528                 :             : 
    1529                 :             : /*
    1530                 :             :  * Emit WAL for invalidations. This currently is only used for commits without
    1531                 :             :  * an xid but which contain invalidations.
    1532                 :             :  */
    1533                 :             : void
    1534                 :       11621 : LogStandbyInvalidations(int nmsgs, SharedInvalidationMessage *msgs,
    1535                 :             :                         bool relcacheInitFileInval)
    1536                 :             : {
    1537                 :             :     xl_invalidations xlrec;
    1538                 :             : 
    1539                 :             :     /* prepare record */
    1540                 :       11621 :     memset(&xlrec, 0, sizeof(xlrec));
    1541                 :       11621 :     xlrec.dbId = MyDatabaseId;
    1542                 :       11621 :     xlrec.tsId = MyDatabaseTableSpace;
    1543                 :       11621 :     xlrec.relcacheInitFileInval = relcacheInitFileInval;
    1544                 :       11621 :     xlrec.nmsgs = nmsgs;
    1545                 :             : 
    1546                 :             :     /* perform insertion */
    1547                 :       11621 :     XLogBeginInsert();
    1548                 :       11621 :     XLogRegisterData(&xlrec, MinSizeOfInvalidations);
    1549                 :       11621 :     XLogRegisterData(msgs,
    1550                 :             :                      nmsgs * sizeof(SharedInvalidationMessage));
    1551                 :       11621 :     XLogInsert(RM_STANDBY_ID, XLOG_INVALIDATIONS);
    1552                 :       11621 : }
    1553                 :             : 
    1554                 :             : /* Return the description of recovery conflict */
    1555                 :             : static const char *
    1556                 :          10 : get_recovery_conflict_desc(RecoveryConflictReason reason)
    1557                 :             : {
    1558                 :          10 :     const char *reasonDesc = _("unknown reason");
    1559                 :             : 
    1560   [ +  +  +  +  :          10 :     switch (reason)
             -  -  -  -  
                      - ]
    1561                 :             :     {
    1562                 :           4 :         case RECOVERY_CONFLICT_BUFFERPIN:
    1563                 :           4 :             reasonDesc = _("recovery conflict on buffer pin");
    1564                 :           4 :             break;
    1565                 :           2 :         case RECOVERY_CONFLICT_LOCK:
    1566                 :           2 :             reasonDesc = _("recovery conflict on lock");
    1567                 :           2 :             break;
    1568                 :           2 :         case RECOVERY_CONFLICT_TABLESPACE:
    1569                 :           2 :             reasonDesc = _("recovery conflict on tablespace");
    1570                 :           2 :             break;
    1571                 :           2 :         case RECOVERY_CONFLICT_SNAPSHOT:
    1572                 :           2 :             reasonDesc = _("recovery conflict on snapshot");
    1573                 :           2 :             break;
    1574                 :           0 :         case RECOVERY_CONFLICT_LOGICALSLOT:
    1575                 :           0 :             reasonDesc = _("recovery conflict on replication slot");
    1576                 :           0 :             break;
    1577                 :           0 :         case RECOVERY_CONFLICT_STARTUP_DEADLOCK:
    1578                 :           0 :             reasonDesc = _("recovery conflict on deadlock");
    1579                 :           0 :             break;
    1580                 :           0 :         case RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK:
    1581                 :           0 :             reasonDesc = _("recovery conflict on buffer deadlock");
    1582                 :           0 :             break;
    1583                 :           0 :         case RECOVERY_CONFLICT_DATABASE:
    1584                 :           0 :             reasonDesc = _("recovery conflict on database");
    1585                 :           0 :             break;
    1586                 :             :     }
    1587                 :             : 
    1588                 :          10 :     return reasonDesc;
    1589                 :             : }
        

Generated by: LCOV version 2.0-1