LCOV - code coverage report
Current view: top level - src/backend/replication - walsender.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 1271 1387 91.6 %
Date: 2025-09-01 09:18:58 Functions: 60 60 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * walsender.c
       4             :  *
       5             :  * The WAL sender process (walsender) is new as of Postgres 9.0. It takes
       6             :  * care of sending XLOG from the primary server to a single recipient.
       7             :  * (Note that there can be more than one walsender process concurrently.)
       8             :  * It is started by the postmaster when the walreceiver of a standby server
       9             :  * connects to the primary server and requests XLOG streaming replication.
      10             :  *
      11             :  * A walsender is similar to a regular backend, ie. there is a one-to-one
      12             :  * relationship between a connection and a walsender process, but instead
      13             :  * of processing SQL queries, it understands a small set of special
      14             :  * replication-mode commands. The START_REPLICATION command begins streaming
      15             :  * WAL to the client. While streaming, the walsender keeps reading XLOG
      16             :  * records from the disk and sends them to the standby server over the
      17             :  * COPY protocol, until either side ends the replication by exiting COPY
      18             :  * mode (or until the connection is closed).
      19             :  *
      20             :  * Normal termination is by SIGTERM, which instructs the walsender to
      21             :  * close the connection and exit(0) at the next convenient moment. Emergency
      22             :  * termination is by SIGQUIT; like any backend, the walsender will simply
      23             :  * abort and exit on SIGQUIT. A close of the connection and a FATAL error
      24             :  * are treated as not a crash but approximately normal termination;
      25             :  * the walsender will exit quickly without sending any more XLOG records.
      26             :  *
      27             :  * If the server is shut down, checkpointer sends us
      28             :  * PROCSIG_WALSND_INIT_STOPPING after all regular backends have exited.  If
      29             :  * the backend is idle or runs an SQL query this causes the backend to
      30             :  * shutdown, if logical replication is in progress all existing WAL records
      31             :  * are processed followed by a shutdown.  Otherwise this causes the walsender
      32             :  * to switch to the "stopping" state. In this state, the walsender will reject
      33             :  * any further replication commands. The checkpointer begins the shutdown
      34             :  * checkpoint once all walsenders are confirmed as stopping. When the shutdown
      35             :  * checkpoint finishes, the postmaster sends us SIGUSR2. This instructs
      36             :  * walsender to send any outstanding WAL, including the shutdown checkpoint
      37             :  * record, wait for it to be replicated to the standby, and then exit.
      38             :  *
      39             :  *
      40             :  * Portions Copyright (c) 2010-2025, PostgreSQL Global Development Group
      41             :  *
      42             :  * IDENTIFICATION
      43             :  *    src/backend/replication/walsender.c
      44             :  *
      45             :  *-------------------------------------------------------------------------
      46             :  */
      47             : #include "postgres.h"
      48             : 
      49             : #include <signal.h>
      50             : #include <unistd.h>
      51             : 
      52             : #include "access/timeline.h"
      53             : #include "access/transam.h"
      54             : #include "access/xact.h"
      55             : #include "access/xlog_internal.h"
      56             : #include "access/xlogreader.h"
      57             : #include "access/xlogrecovery.h"
      58             : #include "access/xlogutils.h"
      59             : #include "backup/basebackup.h"
      60             : #include "backup/basebackup_incremental.h"
      61             : #include "catalog/pg_authid.h"
      62             : #include "catalog/pg_type.h"
      63             : #include "commands/defrem.h"
      64             : #include "funcapi.h"
      65             : #include "libpq/libpq.h"
      66             : #include "libpq/pqformat.h"
      67             : #include "libpq/protocol.h"
      68             : #include "miscadmin.h"
      69             : #include "nodes/replnodes.h"
      70             : #include "pgstat.h"
      71             : #include "postmaster/interrupt.h"
      72             : #include "replication/decode.h"
      73             : #include "replication/logical.h"
      74             : #include "replication/slotsync.h"
      75             : #include "replication/slot.h"
      76             : #include "replication/snapbuild.h"
      77             : #include "replication/syncrep.h"
      78             : #include "replication/walreceiver.h"
      79             : #include "replication/walsender.h"
      80             : #include "replication/walsender_private.h"
      81             : #include "storage/condition_variable.h"
      82             : #include "storage/aio_subsys.h"
      83             : #include "storage/fd.h"
      84             : #include "storage/ipc.h"
      85             : #include "storage/pmsignal.h"
      86             : #include "storage/proc.h"
      87             : #include "storage/procarray.h"
      88             : #include "tcop/dest.h"
      89             : #include "tcop/tcopprot.h"
      90             : #include "utils/acl.h"
      91             : #include "utils/builtins.h"
      92             : #include "utils/guc.h"
      93             : #include "utils/lsyscache.h"
      94             : #include "utils/memutils.h"
      95             : #include "utils/pg_lsn.h"
      96             : #include "utils/pgstat_internal.h"
      97             : #include "utils/ps_status.h"
      98             : #include "utils/timeout.h"
      99             : #include "utils/timestamp.h"
     100             : 
     101             : /* Minimum interval used by walsender for stats flushes, in ms */
     102             : #define WALSENDER_STATS_FLUSH_INTERVAL         1000
     103             : 
     104             : /*
     105             :  * Maximum data payload in a WAL data message.  Must be >= XLOG_BLCKSZ.
     106             :  *
     107             :  * We don't have a good idea of what a good value would be; there's some
     108             :  * overhead per message in both walsender and walreceiver, but on the other
     109             :  * hand sending large batches makes walsender less responsive to signals
     110             :  * because signals are checked only between messages.  128kB (with
     111             :  * default 8k blocks) seems like a reasonable guess for now.
     112             :  */
     113             : #define MAX_SEND_SIZE (XLOG_BLCKSZ * 16)
     114             : 
     115             : /* Array of WalSnds in shared memory */
     116             : WalSndCtlData *WalSndCtl = NULL;
     117             : 
     118             : /* My slot in the shared memory array */
     119             : WalSnd     *MyWalSnd = NULL;
     120             : 
     121             : /* Global state */
     122             : bool        am_walsender = false;   /* Am I a walsender process? */
     123             : bool        am_cascading_walsender = false; /* Am I cascading WAL to another
     124             :                                              * standby? */
     125             : bool        am_db_walsender = false;    /* Connected to a database? */
     126             : 
     127             : /* GUC variables */
     128             : int         max_wal_senders = 10;   /* the maximum number of concurrent
     129             :                                      * walsenders */
     130             : int         wal_sender_timeout = 60 * 1000; /* maximum time to send one WAL
     131             :                                              * data message */
     132             : bool        log_replication_commands = false;
     133             : 
     134             : /*
     135             :  * State for WalSndWakeupRequest
     136             :  */
     137             : bool        wake_wal_senders = false;
     138             : 
     139             : /*
     140             :  * xlogreader used for replication.  Note that a WAL sender doing physical
     141             :  * replication does not need xlogreader to read WAL, but it needs one to
     142             :  * keep a state of its work.
     143             :  */
     144             : static XLogReaderState *xlogreader = NULL;
     145             : 
     146             : /*
     147             :  * If the UPLOAD_MANIFEST command is used to provide a backup manifest in
     148             :  * preparation for an incremental backup, uploaded_manifest will be point
     149             :  * to an object containing information about its contexts, and
     150             :  * uploaded_manifest_mcxt will point to the memory context that contains
     151             :  * that object and all of its subordinate data. Otherwise, both values will
     152             :  * be NULL.
     153             :  */
     154             : static IncrementalBackupInfo *uploaded_manifest = NULL;
     155             : static MemoryContext uploaded_manifest_mcxt = NULL;
     156             : 
     157             : /*
     158             :  * These variables keep track of the state of the timeline we're currently
     159             :  * sending. sendTimeLine identifies the timeline. If sendTimeLineIsHistoric,
     160             :  * the timeline is not the latest timeline on this server, and the server's
     161             :  * history forked off from that timeline at sendTimeLineValidUpto.
     162             :  */
     163             : static TimeLineID sendTimeLine = 0;
     164             : static TimeLineID sendTimeLineNextTLI = 0;
     165             : static bool sendTimeLineIsHistoric = false;
     166             : static XLogRecPtr sendTimeLineValidUpto = InvalidXLogRecPtr;
     167             : 
     168             : /*
     169             :  * How far have we sent WAL already? This is also advertised in
     170             :  * MyWalSnd->sentPtr.  (Actually, this is the next WAL location to send.)
     171             :  */
     172             : static XLogRecPtr sentPtr = InvalidXLogRecPtr;
     173             : 
     174             : /* Buffers for constructing outgoing messages and processing reply messages. */
     175             : static StringInfoData output_message;
     176             : static StringInfoData reply_message;
     177             : static StringInfoData tmpbuf;
     178             : 
     179             : /* Timestamp of last ProcessRepliesIfAny(). */
     180             : static TimestampTz last_processing = 0;
     181             : 
     182             : /*
     183             :  * Timestamp of last ProcessRepliesIfAny() that saw a reply from the
     184             :  * standby. Set to 0 if wal_sender_timeout doesn't need to be active.
     185             :  */
     186             : static TimestampTz last_reply_timestamp = 0;
     187             : 
     188             : /* Have we sent a heartbeat message asking for reply, since last reply? */
     189             : static bool waiting_for_ping_response = false;
     190             : 
     191             : /*
     192             :  * While streaming WAL in Copy mode, streamingDoneSending is set to true
     193             :  * after we have sent CopyDone. We should not send any more CopyData messages
     194             :  * after that. streamingDoneReceiving is set to true when we receive CopyDone
     195             :  * from the other end. When both become true, it's time to exit Copy mode.
     196             :  */
     197             : static bool streamingDoneSending;
     198             : static bool streamingDoneReceiving;
     199             : 
     200             : /* Are we there yet? */
     201             : static bool WalSndCaughtUp = false;
     202             : 
     203             : /* Flags set by signal handlers for later service in main loop */
     204             : static volatile sig_atomic_t got_SIGUSR2 = false;
     205             : static volatile sig_atomic_t got_STOPPING = false;
     206             : 
     207             : /*
     208             :  * This is set while we are streaming. When not set
     209             :  * PROCSIG_WALSND_INIT_STOPPING signal will be handled like SIGTERM. When set,
     210             :  * the main loop is responsible for checking got_STOPPING and terminating when
     211             :  * it's set (after streaming any remaining WAL).
     212             :  */
     213             : static volatile sig_atomic_t replication_active = false;
     214             : 
     215             : static LogicalDecodingContext *logical_decoding_ctx = NULL;
     216             : 
     217             : /* A sample associating a WAL location with the time it was written. */
     218             : typedef struct
     219             : {
     220             :     XLogRecPtr  lsn;
     221             :     TimestampTz time;
     222             : } WalTimeSample;
     223             : 
     224             : /* The size of our buffer of time samples. */
     225             : #define LAG_TRACKER_BUFFER_SIZE 8192
     226             : 
     227             : /* A mechanism for tracking replication lag. */
     228             : typedef struct
     229             : {
     230             :     XLogRecPtr  last_lsn;
     231             :     WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE];
     232             :     int         write_head;
     233             :     int         read_heads[NUM_SYNC_REP_WAIT_MODE];
     234             :     WalTimeSample last_read[NUM_SYNC_REP_WAIT_MODE];
     235             : } LagTracker;
     236             : 
     237             : static LagTracker *lag_tracker;
     238             : 
     239             : /* Signal handlers */
     240             : static void WalSndLastCycleHandler(SIGNAL_ARGS);
     241             : 
     242             : /* Prototypes for private functions */
     243             : typedef void (*WalSndSendDataCallback) (void);
     244             : static void WalSndLoop(WalSndSendDataCallback send_data);
     245             : static void InitWalSenderSlot(void);
     246             : static void WalSndKill(int code, Datum arg);
     247             : pg_noreturn static void WalSndShutdown(void);
     248             : static void XLogSendPhysical(void);
     249             : static void XLogSendLogical(void);
     250             : static void WalSndDone(WalSndSendDataCallback send_data);
     251             : static void IdentifySystem(void);
     252             : static void UploadManifest(void);
     253             : static bool HandleUploadManifestPacket(StringInfo buf, off_t *offset,
     254             :                                        IncrementalBackupInfo *ib);
     255             : static void ReadReplicationSlot(ReadReplicationSlotCmd *cmd);
     256             : static void CreateReplicationSlot(CreateReplicationSlotCmd *cmd);
     257             : static void DropReplicationSlot(DropReplicationSlotCmd *cmd);
     258             : static void StartReplication(StartReplicationCmd *cmd);
     259             : static void StartLogicalReplication(StartReplicationCmd *cmd);
     260             : static void ProcessStandbyMessage(void);
     261             : static void ProcessStandbyReplyMessage(void);
     262             : static void ProcessStandbyHSFeedbackMessage(void);
     263             : static void ProcessStandbyPSRequestMessage(void);
     264             : static void ProcessRepliesIfAny(void);
     265             : static void ProcessPendingWrites(void);
     266             : static void WalSndKeepalive(bool requestReply, XLogRecPtr writePtr);
     267             : static void WalSndKeepaliveIfNecessary(void);
     268             : static void WalSndCheckTimeOut(void);
     269             : static long WalSndComputeSleeptime(TimestampTz now);
     270             : static void WalSndWait(uint32 socket_events, long timeout, uint32 wait_event);
     271             : static void WalSndPrepareWrite(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write);
     272             : static void WalSndWriteData(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write);
     273             : static void WalSndUpdateProgress(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid,
     274             :                                  bool skipped_xact);
     275             : static XLogRecPtr WalSndWaitForWal(XLogRecPtr loc);
     276             : static void LagTrackerWrite(XLogRecPtr lsn, TimestampTz local_flush_time);
     277             : static TimeOffset LagTrackerRead(int head, XLogRecPtr lsn, TimestampTz now);
     278             : static bool TransactionIdInRecentPast(TransactionId xid, uint32 epoch);
     279             : 
     280             : static void WalSndSegmentOpen(XLogReaderState *state, XLogSegNo nextSegNo,
     281             :                               TimeLineID *tli_p);
     282             : 
     283             : 
     284             : /* Initialize walsender process before entering the main command loop */
     285             : void
     286        2282 : InitWalSender(void)
     287             : {
     288        2282 :     am_cascading_walsender = RecoveryInProgress();
     289             : 
     290             :     /* Create a per-walsender data structure in shared memory */
     291        2282 :     InitWalSenderSlot();
     292             : 
     293             :     /* need resource owner for e.g. basebackups */
     294        2282 :     CreateAuxProcessResourceOwner();
     295             : 
     296             :     /*
     297             :      * Let postmaster know that we're a WAL sender. Once we've declared us as
     298             :      * a WAL sender process, postmaster will let us outlive the bgwriter and
     299             :      * kill us last in the shutdown sequence, so we get a chance to stream all
     300             :      * remaining WAL at shutdown, including the shutdown checkpoint. Note that
     301             :      * there's no going back, and we mustn't write any WAL records after this.
     302             :      */
     303        2282 :     MarkPostmasterChildWalSender();
     304        2282 :     SendPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE);
     305             : 
     306             :     /*
     307             :      * If the client didn't specify a database to connect to, show in PGPROC
     308             :      * that our advertised xmin should affect vacuum horizons in all
     309             :      * databases.  This allows physical replication clients to send hot
     310             :      * standby feedback that will delay vacuum cleanup in all databases.
     311             :      */
     312        2282 :     if (MyDatabaseId == InvalidOid)
     313             :     {
     314             :         Assert(MyProc->xmin == InvalidTransactionId);
     315         906 :         LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
     316         906 :         MyProc->statusFlags |= PROC_AFFECTS_ALL_HORIZONS;
     317         906 :         ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
     318         906 :         LWLockRelease(ProcArrayLock);
     319             :     }
     320             : 
     321             :     /* Initialize empty timestamp buffer for lag tracking. */
     322        2282 :     lag_tracker = MemoryContextAllocZero(TopMemoryContext, sizeof(LagTracker));
     323        2282 : }
     324             : 
     325             : /*
     326             :  * Clean up after an error.
     327             :  *
     328             :  * WAL sender processes don't use transactions like regular backends do.
     329             :  * This function does any cleanup required after an error in a WAL sender
     330             :  * process, similar to what transaction abort does in a regular backend.
     331             :  */
     332             : void
     333          96 : WalSndErrorCleanup(void)
     334             : {
     335          96 :     LWLockReleaseAll();
     336          96 :     ConditionVariableCancelSleep();
     337          96 :     pgstat_report_wait_end();
     338          96 :     pgaio_error_cleanup();
     339             : 
     340          96 :     if (xlogreader != NULL && xlogreader->seg.ws_file >= 0)
     341          12 :         wal_segment_close(xlogreader);
     342             : 
     343          96 :     if (MyReplicationSlot != NULL)
     344          30 :         ReplicationSlotRelease();
     345             : 
     346          96 :     ReplicationSlotCleanup(false);
     347             : 
     348          96 :     replication_active = false;
     349             : 
     350             :     /*
     351             :      * If there is a transaction in progress, it will clean up our
     352             :      * ResourceOwner, but if a replication command set up a resource owner
     353             :      * without a transaction, we've got to clean that up now.
     354             :      */
     355          96 :     if (!IsTransactionOrTransactionBlock())
     356          94 :         ReleaseAuxProcessResources(false);
     357             : 
     358          96 :     if (got_STOPPING || got_SIGUSR2)
     359           0 :         proc_exit(0);
     360             : 
     361             :     /* Revert back to startup state */
     362          96 :     WalSndSetState(WALSNDSTATE_STARTUP);
     363          96 : }
     364             : 
     365             : /*
     366             :  * Handle a client's connection abort in an orderly manner.
     367             :  */
     368             : static void
     369          58 : WalSndShutdown(void)
     370             : {
     371             :     /*
     372             :      * Reset whereToSendOutput to prevent ereport from attempting to send any
     373             :      * more messages to the standby.
     374             :      */
     375          58 :     if (whereToSendOutput == DestRemote)
     376          58 :         whereToSendOutput = DestNone;
     377             : 
     378          58 :     proc_exit(0);
     379             :     abort();                    /* keep the compiler quiet */
     380             : }
     381             : 
     382             : /*
     383             :  * Handle the IDENTIFY_SYSTEM command.
     384             :  */
     385             : static void
     386        1412 : IdentifySystem(void)
     387             : {
     388             :     char        sysid[32];
     389             :     char        xloc[MAXFNAMELEN];
     390             :     XLogRecPtr  logptr;
     391        1412 :     char       *dbname = NULL;
     392             :     DestReceiver *dest;
     393             :     TupOutputState *tstate;
     394             :     TupleDesc   tupdesc;
     395             :     Datum       values[4];
     396        1412 :     bool        nulls[4] = {0};
     397             :     TimeLineID  currTLI;
     398             : 
     399             :     /*
     400             :      * Reply with a result set with one row, four columns. First col is system
     401             :      * ID, second is timeline ID, third is current xlog location and the
     402             :      * fourth contains the database name if we are connected to one.
     403             :      */
     404             : 
     405        1412 :     snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
     406             :              GetSystemIdentifier());
     407             : 
     408        1412 :     am_cascading_walsender = RecoveryInProgress();
     409        1412 :     if (am_cascading_walsender)
     410         116 :         logptr = GetStandbyFlushRecPtr(&currTLI);
     411             :     else
     412        1296 :         logptr = GetFlushRecPtr(&currTLI);
     413             : 
     414        1412 :     snprintf(xloc, sizeof(xloc), "%X/%08X", LSN_FORMAT_ARGS(logptr));
     415             : 
     416        1412 :     if (MyDatabaseId != InvalidOid)
     417             :     {
     418         506 :         MemoryContext cur = CurrentMemoryContext;
     419             : 
     420             :         /* syscache access needs a transaction env. */
     421         506 :         StartTransactionCommand();
     422         506 :         dbname = get_database_name(MyDatabaseId);
     423             :         /* copy dbname out of TX context */
     424         506 :         dbname = MemoryContextStrdup(cur, dbname);
     425         506 :         CommitTransactionCommand();
     426             :     }
     427             : 
     428        1412 :     dest = CreateDestReceiver(DestRemoteSimple);
     429             : 
     430             :     /* need a tuple descriptor representing four columns */
     431        1412 :     tupdesc = CreateTemplateTupleDesc(4);
     432        1412 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "systemid",
     433             :                               TEXTOID, -1, 0);
     434        1412 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "timeline",
     435             :                               INT8OID, -1, 0);
     436        1412 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 3, "xlogpos",
     437             :                               TEXTOID, -1, 0);
     438        1412 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 4, "dbname",
     439             :                               TEXTOID, -1, 0);
     440             : 
     441             :     /* prepare for projection of tuples */
     442        1412 :     tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
     443             : 
     444             :     /* column 1: system identifier */
     445        1412 :     values[0] = CStringGetTextDatum(sysid);
     446             : 
     447             :     /* column 2: timeline */
     448        1412 :     values[1] = Int64GetDatum(currTLI);
     449             : 
     450             :     /* column 3: wal location */
     451        1412 :     values[2] = CStringGetTextDatum(xloc);
     452             : 
     453             :     /* column 4: database name, or NULL if none */
     454        1412 :     if (dbname)
     455         506 :         values[3] = CStringGetTextDatum(dbname);
     456             :     else
     457         906 :         nulls[3] = true;
     458             : 
     459             :     /* send it to dest */
     460        1412 :     do_tup_output(tstate, values, nulls);
     461             : 
     462        1412 :     end_tup_output(tstate);
     463        1412 : }
     464             : 
     465             : /* Handle READ_REPLICATION_SLOT command */
     466             : static void
     467          12 : ReadReplicationSlot(ReadReplicationSlotCmd *cmd)
     468             : {
     469             : #define READ_REPLICATION_SLOT_COLS 3
     470             :     ReplicationSlot *slot;
     471             :     DestReceiver *dest;
     472             :     TupOutputState *tstate;
     473             :     TupleDesc   tupdesc;
     474          12 :     Datum       values[READ_REPLICATION_SLOT_COLS] = {0};
     475             :     bool        nulls[READ_REPLICATION_SLOT_COLS];
     476             : 
     477          12 :     tupdesc = CreateTemplateTupleDesc(READ_REPLICATION_SLOT_COLS);
     478          12 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "slot_type",
     479             :                               TEXTOID, -1, 0);
     480          12 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "restart_lsn",
     481             :                               TEXTOID, -1, 0);
     482             :     /* TimeLineID is unsigned, so int4 is not wide enough. */
     483          12 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 3, "restart_tli",
     484             :                               INT8OID, -1, 0);
     485             : 
     486          12 :     memset(nulls, true, READ_REPLICATION_SLOT_COLS * sizeof(bool));
     487             : 
     488          12 :     LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
     489          12 :     slot = SearchNamedReplicationSlot(cmd->slotname, false);
     490          12 :     if (slot == NULL || !slot->in_use)
     491             :     {
     492           4 :         LWLockRelease(ReplicationSlotControlLock);
     493             :     }
     494             :     else
     495             :     {
     496             :         ReplicationSlot slot_contents;
     497           8 :         int         i = 0;
     498             : 
     499             :         /* Copy slot contents while holding spinlock */
     500           8 :         SpinLockAcquire(&slot->mutex);
     501           8 :         slot_contents = *slot;
     502           8 :         SpinLockRelease(&slot->mutex);
     503           8 :         LWLockRelease(ReplicationSlotControlLock);
     504             : 
     505           8 :         if (OidIsValid(slot_contents.data.database))
     506           2 :             ereport(ERROR,
     507             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     508             :                     errmsg("cannot use %s with a logical replication slot",
     509             :                            "READ_REPLICATION_SLOT"));
     510             : 
     511             :         /* slot type */
     512           6 :         values[i] = CStringGetTextDatum("physical");
     513           6 :         nulls[i] = false;
     514           6 :         i++;
     515             : 
     516             :         /* start LSN */
     517           6 :         if (!XLogRecPtrIsInvalid(slot_contents.data.restart_lsn))
     518             :         {
     519             :             char        xloc[64];
     520             : 
     521           6 :             snprintf(xloc, sizeof(xloc), "%X/%08X",
     522           6 :                      LSN_FORMAT_ARGS(slot_contents.data.restart_lsn));
     523           6 :             values[i] = CStringGetTextDatum(xloc);
     524           6 :             nulls[i] = false;
     525             :         }
     526           6 :         i++;
     527             : 
     528             :         /* timeline this WAL was produced on */
     529           6 :         if (!XLogRecPtrIsInvalid(slot_contents.data.restart_lsn))
     530             :         {
     531             :             TimeLineID  slots_position_timeline;
     532             :             TimeLineID  current_timeline;
     533           6 :             List       *timeline_history = NIL;
     534             : 
     535             :             /*
     536             :              * While in recovery, use as timeline the currently-replaying one
     537             :              * to get the LSN position's history.
     538             :              */
     539           6 :             if (RecoveryInProgress())
     540           0 :                 (void) GetXLogReplayRecPtr(&current_timeline);
     541             :             else
     542           6 :                 current_timeline = GetWALInsertionTimeLine();
     543             : 
     544           6 :             timeline_history = readTimeLineHistory(current_timeline);
     545           6 :             slots_position_timeline = tliOfPointInHistory(slot_contents.data.restart_lsn,
     546             :                                                           timeline_history);
     547           6 :             values[i] = Int64GetDatum((int64) slots_position_timeline);
     548           6 :             nulls[i] = false;
     549             :         }
     550           6 :         i++;
     551             : 
     552             :         Assert(i == READ_REPLICATION_SLOT_COLS);
     553             :     }
     554             : 
     555          10 :     dest = CreateDestReceiver(DestRemoteSimple);
     556          10 :     tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
     557          10 :     do_tup_output(tstate, values, nulls);
     558          10 :     end_tup_output(tstate);
     559          10 : }
     560             : 
     561             : 
     562             : /*
     563             :  * Handle TIMELINE_HISTORY command.
     564             :  */
     565             : static void
     566          28 : SendTimeLineHistory(TimeLineHistoryCmd *cmd)
     567             : {
     568             :     DestReceiver *dest;
     569             :     TupleDesc   tupdesc;
     570             :     StringInfoData buf;
     571             :     char        histfname[MAXFNAMELEN];
     572             :     char        path[MAXPGPATH];
     573             :     int         fd;
     574             :     off_t       histfilelen;
     575             :     off_t       bytesleft;
     576             :     Size        len;
     577             : 
     578          28 :     dest = CreateDestReceiver(DestRemoteSimple);
     579             : 
     580             :     /*
     581             :      * Reply with a result set with one row, and two columns. The first col is
     582             :      * the name of the history file, 2nd is the contents.
     583             :      */
     584          28 :     tupdesc = CreateTemplateTupleDesc(2);
     585          28 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "filename", TEXTOID, -1, 0);
     586          28 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "content", TEXTOID, -1, 0);
     587             : 
     588          28 :     TLHistoryFileName(histfname, cmd->timeline);
     589          28 :     TLHistoryFilePath(path, cmd->timeline);
     590             : 
     591             :     /* Send a RowDescription message */
     592          28 :     dest->rStartup(dest, CMD_SELECT, tupdesc);
     593             : 
     594             :     /* Send a DataRow message */
     595          28 :     pq_beginmessage(&buf, PqMsg_DataRow);
     596          28 :     pq_sendint16(&buf, 2);      /* # of columns */
     597          28 :     len = strlen(histfname);
     598          28 :     pq_sendint32(&buf, len);    /* col1 len */
     599          28 :     pq_sendbytes(&buf, histfname, len);
     600             : 
     601          28 :     fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
     602          28 :     if (fd < 0)
     603           0 :         ereport(ERROR,
     604             :                 (errcode_for_file_access(),
     605             :                  errmsg("could not open file \"%s\": %m", path)));
     606             : 
     607             :     /* Determine file length and send it to client */
     608          28 :     histfilelen = lseek(fd, 0, SEEK_END);
     609          28 :     if (histfilelen < 0)
     610           0 :         ereport(ERROR,
     611             :                 (errcode_for_file_access(),
     612             :                  errmsg("could not seek to end of file \"%s\": %m", path)));
     613          28 :     if (lseek(fd, 0, SEEK_SET) != 0)
     614           0 :         ereport(ERROR,
     615             :                 (errcode_for_file_access(),
     616             :                  errmsg("could not seek to beginning of file \"%s\": %m", path)));
     617             : 
     618          28 :     pq_sendint32(&buf, histfilelen);    /* col2 len */
     619             : 
     620          28 :     bytesleft = histfilelen;
     621          56 :     while (bytesleft > 0)
     622             :     {
     623             :         PGAlignedBlock rbuf;
     624             :         int         nread;
     625             : 
     626          28 :         pgstat_report_wait_start(WAIT_EVENT_WALSENDER_TIMELINE_HISTORY_READ);
     627          28 :         nread = read(fd, rbuf.data, sizeof(rbuf));
     628          28 :         pgstat_report_wait_end();
     629          28 :         if (nread < 0)
     630           0 :             ereport(ERROR,
     631             :                     (errcode_for_file_access(),
     632             :                      errmsg("could not read file \"%s\": %m",
     633             :                             path)));
     634          28 :         else if (nread == 0)
     635           0 :             ereport(ERROR,
     636             :                     (errcode(ERRCODE_DATA_CORRUPTED),
     637             :                      errmsg("could not read file \"%s\": read %d of %zu",
     638             :                             path, nread, (Size) bytesleft)));
     639             : 
     640          28 :         pq_sendbytes(&buf, rbuf.data, nread);
     641          28 :         bytesleft -= nread;
     642             :     }
     643             : 
     644          28 :     if (CloseTransientFile(fd) != 0)
     645           0 :         ereport(ERROR,
     646             :                 (errcode_for_file_access(),
     647             :                  errmsg("could not close file \"%s\": %m", path)));
     648             : 
     649          28 :     pq_endmessage(&buf);
     650          28 : }
     651             : 
     652             : /*
     653             :  * Handle UPLOAD_MANIFEST command.
     654             :  */
     655             : static void
     656          22 : UploadManifest(void)
     657             : {
     658             :     MemoryContext mcxt;
     659             :     IncrementalBackupInfo *ib;
     660          22 :     off_t       offset = 0;
     661             :     StringInfoData buf;
     662             : 
     663             :     /*
     664             :      * parsing the manifest will use the cryptohash stuff, which requires a
     665             :      * resource owner
     666             :      */
     667             :     Assert(AuxProcessResourceOwner != NULL);
     668             :     Assert(CurrentResourceOwner == AuxProcessResourceOwner ||
     669             :            CurrentResourceOwner == NULL);
     670          22 :     CurrentResourceOwner = AuxProcessResourceOwner;
     671             : 
     672             :     /* Prepare to read manifest data into a temporary context. */
     673          22 :     mcxt = AllocSetContextCreate(CurrentMemoryContext,
     674             :                                  "incremental backup information",
     675             :                                  ALLOCSET_DEFAULT_SIZES);
     676          22 :     ib = CreateIncrementalBackupInfo(mcxt);
     677             : 
     678             :     /* Send a CopyInResponse message */
     679          22 :     pq_beginmessage(&buf, PqMsg_CopyInResponse);
     680          22 :     pq_sendbyte(&buf, 0);
     681          22 :     pq_sendint16(&buf, 0);
     682          22 :     pq_endmessage_reuse(&buf);
     683          22 :     pq_flush();
     684             : 
     685             :     /* Receive packets from client until done. */
     686          86 :     while (HandleUploadManifestPacket(&buf, &offset, ib))
     687             :         ;
     688             : 
     689             :     /* Finish up manifest processing. */
     690          20 :     FinalizeIncrementalManifest(ib);
     691             : 
     692             :     /*
     693             :      * Discard any old manifest information and arrange to preserve the new
     694             :      * information we just got.
     695             :      *
     696             :      * We assume that MemoryContextDelete and MemoryContextSetParent won't
     697             :      * fail, and thus we shouldn't end up bailing out of here in such a way as
     698             :      * to leave dangling pointers.
     699             :      */
     700          20 :     if (uploaded_manifest_mcxt != NULL)
     701           0 :         MemoryContextDelete(uploaded_manifest_mcxt);
     702          20 :     MemoryContextSetParent(mcxt, CacheMemoryContext);
     703          20 :     uploaded_manifest = ib;
     704          20 :     uploaded_manifest_mcxt = mcxt;
     705             : 
     706             :     /* clean up the resource owner we created */
     707          20 :     ReleaseAuxProcessResources(true);
     708          20 : }
     709             : 
     710             : /*
     711             :  * Process one packet received during the handling of an UPLOAD_MANIFEST
     712             :  * operation.
     713             :  *
     714             :  * 'buf' is scratch space. This function expects it to be initialized, doesn't
     715             :  * care what the current contents are, and may override them with completely
     716             :  * new contents.
     717             :  *
     718             :  * The return value is true if the caller should continue processing
     719             :  * additional packets and false if the UPLOAD_MANIFEST operation is complete.
     720             :  */
     721             : static bool
     722          86 : HandleUploadManifestPacket(StringInfo buf, off_t *offset,
     723             :                            IncrementalBackupInfo *ib)
     724             : {
     725             :     int         mtype;
     726             :     int         maxmsglen;
     727             : 
     728          86 :     HOLD_CANCEL_INTERRUPTS();
     729             : 
     730          86 :     pq_startmsgread();
     731          86 :     mtype = pq_getbyte();
     732          86 :     if (mtype == EOF)
     733           0 :         ereport(ERROR,
     734             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
     735             :                  errmsg("unexpected EOF on client connection with an open transaction")));
     736             : 
     737          86 :     switch (mtype)
     738             :     {
     739          66 :         case PqMsg_CopyData:
     740          66 :             maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
     741          66 :             break;
     742          20 :         case PqMsg_CopyDone:
     743             :         case PqMsg_CopyFail:
     744             :         case PqMsg_Flush:
     745             :         case PqMsg_Sync:
     746          20 :             maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
     747          20 :             break;
     748           0 :         default:
     749           0 :             ereport(ERROR,
     750             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
     751             :                      errmsg("unexpected message type 0x%02X during COPY from stdin",
     752             :                             mtype)));
     753             :             maxmsglen = 0;      /* keep compiler quiet */
     754             :             break;
     755             :     }
     756             : 
     757             :     /* Now collect the message body */
     758          86 :     if (pq_getmessage(buf, maxmsglen))
     759           0 :         ereport(ERROR,
     760             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
     761             :                  errmsg("unexpected EOF on client connection with an open transaction")));
     762          86 :     RESUME_CANCEL_INTERRUPTS();
     763             : 
     764             :     /* Process the message */
     765          86 :     switch (mtype)
     766             :     {
     767          66 :         case PqMsg_CopyData:
     768          66 :             AppendIncrementalManifestData(ib, buf->data, buf->len);
     769          64 :             return true;
     770             : 
     771          20 :         case PqMsg_CopyDone:
     772          20 :             return false;
     773             : 
     774           0 :         case PqMsg_Sync:
     775             :         case PqMsg_Flush:
     776             :             /* Ignore these while in CopyOut mode as we do elsewhere. */
     777           0 :             return true;
     778             : 
     779           0 :         case PqMsg_CopyFail:
     780           0 :             ereport(ERROR,
     781             :                     (errcode(ERRCODE_QUERY_CANCELED),
     782             :                      errmsg("COPY from stdin failed: %s",
     783             :                             pq_getmsgstring(buf))));
     784             :     }
     785             : 
     786             :     /* Not reached. */
     787             :     Assert(false);
     788           0 :     return false;
     789             : }
     790             : 
     791             : /*
     792             :  * Handle START_REPLICATION command.
     793             :  *
     794             :  * At the moment, this never returns, but an ereport(ERROR) will take us back
     795             :  * to the main loop.
     796             :  */
     797             : static void
     798         520 : StartReplication(StartReplicationCmd *cmd)
     799             : {
     800             :     StringInfoData buf;
     801             :     XLogRecPtr  FlushPtr;
     802             :     TimeLineID  FlushTLI;
     803             : 
     804             :     /* create xlogreader for physical replication */
     805         520 :     xlogreader =
     806         520 :         XLogReaderAllocate(wal_segment_size, NULL,
     807         520 :                            XL_ROUTINE(.segment_open = WalSndSegmentOpen,
     808             :                                       .segment_close = wal_segment_close),
     809             :                            NULL);
     810             : 
     811         520 :     if (!xlogreader)
     812           0 :         ereport(ERROR,
     813             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
     814             :                  errmsg("out of memory"),
     815             :                  errdetail("Failed while allocating a WAL reading processor.")));
     816             : 
     817             :     /*
     818             :      * We assume here that we're logging enough information in the WAL for
     819             :      * log-shipping, since this is checked in PostmasterMain().
     820             :      *
     821             :      * NOTE: wal_level can only change at shutdown, so in most cases it is
     822             :      * difficult for there to be WAL data that we can still see that was
     823             :      * written at wal_level='minimal'.
     824             :      */
     825             : 
     826         520 :     if (cmd->slotname)
     827             :     {
     828         358 :         ReplicationSlotAcquire(cmd->slotname, true, true);
     829         354 :         if (SlotIsLogical(MyReplicationSlot))
     830           0 :             ereport(ERROR,
     831             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     832             :                      errmsg("cannot use a logical replication slot for physical replication")));
     833             : 
     834             :         /*
     835             :          * We don't need to verify the slot's restart_lsn here; instead we
     836             :          * rely on the caller requesting the starting point to use.  If the
     837             :          * WAL segment doesn't exist, we'll fail later.
     838             :          */
     839             :     }
     840             : 
     841             :     /*
     842             :      * Select the timeline. If it was given explicitly by the client, use
     843             :      * that. Otherwise use the timeline of the last replayed record.
     844             :      */
     845         516 :     am_cascading_walsender = RecoveryInProgress();
     846         516 :     if (am_cascading_walsender)
     847          26 :         FlushPtr = GetStandbyFlushRecPtr(&FlushTLI);
     848             :     else
     849         490 :         FlushPtr = GetFlushRecPtr(&FlushTLI);
     850             : 
     851         516 :     if (cmd->timeline != 0)
     852             :     {
     853             :         XLogRecPtr  switchpoint;
     854             : 
     855         514 :         sendTimeLine = cmd->timeline;
     856         514 :         if (sendTimeLine == FlushTLI)
     857             :         {
     858         490 :             sendTimeLineIsHistoric = false;
     859         490 :             sendTimeLineValidUpto = InvalidXLogRecPtr;
     860             :         }
     861             :         else
     862             :         {
     863             :             List       *timeLineHistory;
     864             : 
     865          24 :             sendTimeLineIsHistoric = true;
     866             : 
     867             :             /*
     868             :              * Check that the timeline the client requested exists, and the
     869             :              * requested start location is on that timeline.
     870             :              */
     871          24 :             timeLineHistory = readTimeLineHistory(FlushTLI);
     872          24 :             switchpoint = tliSwitchPoint(cmd->timeline, timeLineHistory,
     873             :                                          &sendTimeLineNextTLI);
     874          24 :             list_free_deep(timeLineHistory);
     875             : 
     876             :             /*
     877             :              * Found the requested timeline in the history. Check that
     878             :              * requested startpoint is on that timeline in our history.
     879             :              *
     880             :              * This is quite loose on purpose. We only check that we didn't
     881             :              * fork off the requested timeline before the switchpoint. We
     882             :              * don't check that we switched *to* it before the requested
     883             :              * starting point. This is because the client can legitimately
     884             :              * request to start replication from the beginning of the WAL
     885             :              * segment that contains switchpoint, but on the new timeline, so
     886             :              * that it doesn't end up with a partial segment. If you ask for
     887             :              * too old a starting point, you'll get an error later when we
     888             :              * fail to find the requested WAL segment in pg_wal.
     889             :              *
     890             :              * XXX: we could be more strict here and only allow a startpoint
     891             :              * that's older than the switchpoint, if it's still in the same
     892             :              * WAL segment.
     893             :              */
     894          24 :             if (!XLogRecPtrIsInvalid(switchpoint) &&
     895          24 :                 switchpoint < cmd->startpoint)
     896             :             {
     897           0 :                 ereport(ERROR,
     898             :                         errmsg("requested starting point %X/%08X on timeline %u is not in this server's history",
     899             :                                LSN_FORMAT_ARGS(cmd->startpoint),
     900             :                                cmd->timeline),
     901             :                         errdetail("This server's history forked from timeline %u at %X/%08X.",
     902             :                                   cmd->timeline,
     903             :                                   LSN_FORMAT_ARGS(switchpoint)));
     904             :             }
     905          24 :             sendTimeLineValidUpto = switchpoint;
     906             :         }
     907             :     }
     908             :     else
     909             :     {
     910           2 :         sendTimeLine = FlushTLI;
     911           2 :         sendTimeLineValidUpto = InvalidXLogRecPtr;
     912           2 :         sendTimeLineIsHistoric = false;
     913             :     }
     914             : 
     915         516 :     streamingDoneSending = streamingDoneReceiving = false;
     916             : 
     917             :     /* If there is nothing to stream, don't even enter COPY mode */
     918         516 :     if (!sendTimeLineIsHistoric || cmd->startpoint < sendTimeLineValidUpto)
     919             :     {
     920             :         /*
     921             :          * When we first start replication the standby will be behind the
     922             :          * primary. For some applications, for example synchronous
     923             :          * replication, it is important to have a clear state for this initial
     924             :          * catchup mode, so we can trigger actions when we change streaming
     925             :          * state later. We may stay in this state for a long time, which is
     926             :          * exactly why we want to be able to monitor whether or not we are
     927             :          * still here.
     928             :          */
     929         516 :         WalSndSetState(WALSNDSTATE_CATCHUP);
     930             : 
     931             :         /* Send a CopyBothResponse message, and start streaming */
     932         516 :         pq_beginmessage(&buf, PqMsg_CopyBothResponse);
     933         516 :         pq_sendbyte(&buf, 0);
     934         516 :         pq_sendint16(&buf, 0);
     935         516 :         pq_endmessage(&buf);
     936         516 :         pq_flush();
     937             : 
     938             :         /*
     939             :          * Don't allow a request to stream from a future point in WAL that
     940             :          * hasn't been flushed to disk in this server yet.
     941             :          */
     942         516 :         if (FlushPtr < cmd->startpoint)
     943             :         {
     944           0 :             ereport(ERROR,
     945             :                     errmsg("requested starting point %X/%08X is ahead of the WAL flush position of this server %X/%08X",
     946             :                            LSN_FORMAT_ARGS(cmd->startpoint),
     947             :                            LSN_FORMAT_ARGS(FlushPtr)));
     948             :         }
     949             : 
     950             :         /* Start streaming from the requested point */
     951         516 :         sentPtr = cmd->startpoint;
     952             : 
     953             :         /* Initialize shared memory status, too */
     954         516 :         SpinLockAcquire(&MyWalSnd->mutex);
     955         516 :         MyWalSnd->sentPtr = sentPtr;
     956         516 :         SpinLockRelease(&MyWalSnd->mutex);
     957             : 
     958         516 :         SyncRepInitConfig();
     959             : 
     960             :         /* Main loop of walsender */
     961         516 :         replication_active = true;
     962             : 
     963         516 :         WalSndLoop(XLogSendPhysical);
     964             : 
     965         298 :         replication_active = false;
     966         298 :         if (got_STOPPING)
     967           0 :             proc_exit(0);
     968         298 :         WalSndSetState(WALSNDSTATE_STARTUP);
     969             : 
     970             :         Assert(streamingDoneSending && streamingDoneReceiving);
     971             :     }
     972             : 
     973         298 :     if (cmd->slotname)
     974         266 :         ReplicationSlotRelease();
     975             : 
     976             :     /*
     977             :      * Copy is finished now. Send a single-row result set indicating the next
     978             :      * timeline.
     979             :      */
     980         298 :     if (sendTimeLineIsHistoric)
     981             :     {
     982             :         char        startpos_str[8 + 1 + 8 + 1];
     983             :         DestReceiver *dest;
     984             :         TupOutputState *tstate;
     985             :         TupleDesc   tupdesc;
     986             :         Datum       values[2];
     987          26 :         bool        nulls[2] = {0};
     988             : 
     989          26 :         snprintf(startpos_str, sizeof(startpos_str), "%X/%08X",
     990          26 :                  LSN_FORMAT_ARGS(sendTimeLineValidUpto));
     991             : 
     992          26 :         dest = CreateDestReceiver(DestRemoteSimple);
     993             : 
     994             :         /*
     995             :          * Need a tuple descriptor representing two columns. int8 may seem
     996             :          * like a surprising data type for this, but in theory int4 would not
     997             :          * be wide enough for this, as TimeLineID is unsigned.
     998             :          */
     999          26 :         tupdesc = CreateTemplateTupleDesc(2);
    1000          26 :         TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "next_tli",
    1001             :                                   INT8OID, -1, 0);
    1002          26 :         TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "next_tli_startpos",
    1003             :                                   TEXTOID, -1, 0);
    1004             : 
    1005             :         /* prepare for projection of tuple */
    1006          26 :         tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
    1007             : 
    1008          26 :         values[0] = Int64GetDatum((int64) sendTimeLineNextTLI);
    1009          26 :         values[1] = CStringGetTextDatum(startpos_str);
    1010             : 
    1011             :         /* send it to dest */
    1012          26 :         do_tup_output(tstate, values, nulls);
    1013             : 
    1014          26 :         end_tup_output(tstate);
    1015             :     }
    1016             : 
    1017             :     /* Send CommandComplete message */
    1018         298 :     EndReplicationCommand("START_STREAMING");
    1019         298 : }
    1020             : 
    1021             : /*
    1022             :  * XLogReaderRoutine->page_read callback for logical decoding contexts, as a
    1023             :  * walsender process.
    1024             :  *
    1025             :  * Inside the walsender we can do better than read_local_xlog_page,
    1026             :  * which has to do a plain sleep/busy loop, because the walsender's latch gets
    1027             :  * set every time WAL is flushed.
    1028             :  */
    1029             : static int
    1030       32392 : logical_read_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen,
    1031             :                        XLogRecPtr targetRecPtr, char *cur_page)
    1032             : {
    1033             :     XLogRecPtr  flushptr;
    1034             :     int         count;
    1035             :     WALReadError errinfo;
    1036             :     XLogSegNo   segno;
    1037             :     TimeLineID  currTLI;
    1038             : 
    1039             :     /*
    1040             :      * Make sure we have enough WAL available before retrieving the current
    1041             :      * timeline.
    1042             :      */
    1043       32392 :     flushptr = WalSndWaitForWal(targetPagePtr + reqLen);
    1044             : 
    1045             :     /* Fail if not enough (implies we are going to shut down) */
    1046       32050 :     if (flushptr < targetPagePtr + reqLen)
    1047        7154 :         return -1;
    1048             : 
    1049             :     /*
    1050             :      * Since logical decoding is also permitted on a standby server, we need
    1051             :      * to check if the server is in recovery to decide how to get the current
    1052             :      * timeline ID (so that it also covers the promotion or timeline change
    1053             :      * cases). We must determine am_cascading_walsender after waiting for the
    1054             :      * required WAL so that it is correct when the walsender wakes up after a
    1055             :      * promotion.
    1056             :      */
    1057       24896 :     am_cascading_walsender = RecoveryInProgress();
    1058             : 
    1059       24896 :     if (am_cascading_walsender)
    1060        1612 :         GetXLogReplayRecPtr(&currTLI);
    1061             :     else
    1062       23284 :         currTLI = GetWALInsertionTimeLine();
    1063             : 
    1064       24896 :     XLogReadDetermineTimeline(state, targetPagePtr, reqLen, currTLI);
    1065       24896 :     sendTimeLineIsHistoric = (state->currTLI != currTLI);
    1066       24896 :     sendTimeLine = state->currTLI;
    1067       24896 :     sendTimeLineValidUpto = state->currTLIValidUntil;
    1068       24896 :     sendTimeLineNextTLI = state->nextTLI;
    1069             : 
    1070       24896 :     if (targetPagePtr + XLOG_BLCKSZ <= flushptr)
    1071       21212 :         count = XLOG_BLCKSZ;    /* more than one block available */
    1072             :     else
    1073        3684 :         count = flushptr - targetPagePtr;   /* part of the page available */
    1074             : 
    1075             :     /* now actually read the data, we know it's there */
    1076       24896 :     if (!WALRead(state,
    1077             :                  cur_page,
    1078             :                  targetPagePtr,
    1079             :                  count,
    1080             :                  currTLI,       /* Pass the current TLI because only
    1081             :                                  * WalSndSegmentOpen controls whether new TLI
    1082             :                                  * is needed. */
    1083             :                  &errinfo))
    1084           0 :         WALReadRaiseError(&errinfo);
    1085             : 
    1086             :     /*
    1087             :      * After reading into the buffer, check that what we read was valid. We do
    1088             :      * this after reading, because even though the segment was present when we
    1089             :      * opened it, it might get recycled or removed while we read it. The
    1090             :      * read() succeeds in that case, but the data we tried to read might
    1091             :      * already have been overwritten with new WAL records.
    1092             :      */
    1093       24896 :     XLByteToSeg(targetPagePtr, segno, state->segcxt.ws_segsize);
    1094       24896 :     CheckXLogRemoved(segno, state->seg.ws_tli);
    1095             : 
    1096       24896 :     return count;
    1097             : }
    1098             : 
    1099             : /*
    1100             :  * Process extra options given to CREATE_REPLICATION_SLOT.
    1101             :  */
    1102             : static void
    1103         934 : parseCreateReplSlotOptions(CreateReplicationSlotCmd *cmd,
    1104             :                            bool *reserve_wal,
    1105             :                            CRSSnapshotAction *snapshot_action,
    1106             :                            bool *two_phase, bool *failover)
    1107             : {
    1108             :     ListCell   *lc;
    1109         934 :     bool        snapshot_action_given = false;
    1110         934 :     bool        reserve_wal_given = false;
    1111         934 :     bool        two_phase_given = false;
    1112         934 :     bool        failover_given = false;
    1113             : 
    1114             :     /* Parse options */
    1115        1884 :     foreach(lc, cmd->options)
    1116             :     {
    1117         950 :         DefElem    *defel = (DefElem *) lfirst(lc);
    1118             : 
    1119         950 :         if (strcmp(defel->defname, "snapshot") == 0)
    1120             :         {
    1121             :             char       *action;
    1122             : 
    1123         662 :             if (snapshot_action_given || cmd->kind != REPLICATION_KIND_LOGICAL)
    1124           0 :                 ereport(ERROR,
    1125             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1126             :                          errmsg("conflicting or redundant options")));
    1127             : 
    1128         662 :             action = defGetString(defel);
    1129         662 :             snapshot_action_given = true;
    1130             : 
    1131         662 :             if (strcmp(action, "export") == 0)
    1132           2 :                 *snapshot_action = CRS_EXPORT_SNAPSHOT;
    1133         660 :             else if (strcmp(action, "nothing") == 0)
    1134         274 :                 *snapshot_action = CRS_NOEXPORT_SNAPSHOT;
    1135         386 :             else if (strcmp(action, "use") == 0)
    1136         386 :                 *snapshot_action = CRS_USE_SNAPSHOT;
    1137             :             else
    1138           0 :                 ereport(ERROR,
    1139             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1140             :                          errmsg("unrecognized value for CREATE_REPLICATION_SLOT option \"%s\": \"%s\"",
    1141             :                                 defel->defname, action)));
    1142             :         }
    1143         288 :         else if (strcmp(defel->defname, "reserve_wal") == 0)
    1144             :         {
    1145         270 :             if (reserve_wal_given || cmd->kind != REPLICATION_KIND_PHYSICAL)
    1146           0 :                 ereport(ERROR,
    1147             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1148             :                          errmsg("conflicting or redundant options")));
    1149             : 
    1150         270 :             reserve_wal_given = true;
    1151         270 :             *reserve_wal = defGetBoolean(defel);
    1152             :         }
    1153          18 :         else if (strcmp(defel->defname, "two_phase") == 0)
    1154             :         {
    1155           4 :             if (two_phase_given || cmd->kind != REPLICATION_KIND_LOGICAL)
    1156           0 :                 ereport(ERROR,
    1157             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1158             :                          errmsg("conflicting or redundant options")));
    1159           4 :             two_phase_given = true;
    1160           4 :             *two_phase = defGetBoolean(defel);
    1161             :         }
    1162          14 :         else if (strcmp(defel->defname, "failover") == 0)
    1163             :         {
    1164          14 :             if (failover_given || cmd->kind != REPLICATION_KIND_LOGICAL)
    1165           0 :                 ereport(ERROR,
    1166             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1167             :                          errmsg("conflicting or redundant options")));
    1168          14 :             failover_given = true;
    1169          14 :             *failover = defGetBoolean(defel);
    1170             :         }
    1171             :         else
    1172           0 :             elog(ERROR, "unrecognized option: %s", defel->defname);
    1173             :     }
    1174         934 : }
    1175             : 
    1176             : /*
    1177             :  * Create a new replication slot.
    1178             :  */
    1179             : static void
    1180         934 : CreateReplicationSlot(CreateReplicationSlotCmd *cmd)
    1181             : {
    1182         934 :     const char *snapshot_name = NULL;
    1183             :     char        xloc[MAXFNAMELEN];
    1184             :     char       *slot_name;
    1185         934 :     bool        reserve_wal = false;
    1186         934 :     bool        two_phase = false;
    1187         934 :     bool        failover = false;
    1188         934 :     CRSSnapshotAction snapshot_action = CRS_EXPORT_SNAPSHOT;
    1189             :     DestReceiver *dest;
    1190             :     TupOutputState *tstate;
    1191             :     TupleDesc   tupdesc;
    1192             :     Datum       values[4];
    1193         934 :     bool        nulls[4] = {0};
    1194             : 
    1195             :     Assert(!MyReplicationSlot);
    1196             : 
    1197         934 :     parseCreateReplSlotOptions(cmd, &reserve_wal, &snapshot_action, &two_phase,
    1198             :                                &failover);
    1199             : 
    1200         934 :     if (cmd->kind == REPLICATION_KIND_PHYSICAL)
    1201             :     {
    1202         272 :         ReplicationSlotCreate(cmd->slotname, false,
    1203         272 :                               cmd->temporary ? RS_TEMPORARY : RS_PERSISTENT,
    1204             :                               false, false, false);
    1205             : 
    1206         270 :         if (reserve_wal)
    1207             :         {
    1208         268 :             ReplicationSlotReserveWal();
    1209             : 
    1210         268 :             ReplicationSlotMarkDirty();
    1211             : 
    1212             :             /* Write this slot to disk if it's a permanent one. */
    1213         268 :             if (!cmd->temporary)
    1214           6 :                 ReplicationSlotSave();
    1215             :         }
    1216             :     }
    1217             :     else
    1218             :     {
    1219             :         LogicalDecodingContext *ctx;
    1220         662 :         bool        need_full_snapshot = false;
    1221             : 
    1222             :         Assert(cmd->kind == REPLICATION_KIND_LOGICAL);
    1223             : 
    1224         662 :         CheckLogicalDecodingRequirements();
    1225             : 
    1226             :         /*
    1227             :          * Initially create persistent slot as ephemeral - that allows us to
    1228             :          * nicely handle errors during initialization because it'll get
    1229             :          * dropped if this transaction fails. We'll make it persistent at the
    1230             :          * end. Temporary slots can be created as temporary from beginning as
    1231             :          * they get dropped on error as well.
    1232             :          */
    1233         662 :         ReplicationSlotCreate(cmd->slotname, true,
    1234         662 :                               cmd->temporary ? RS_TEMPORARY : RS_EPHEMERAL,
    1235             :                               two_phase, failover, false);
    1236             : 
    1237             :         /*
    1238             :          * Do options check early so that we can bail before calling the
    1239             :          * DecodingContextFindStartpoint which can take long time.
    1240             :          */
    1241         662 :         if (snapshot_action == CRS_EXPORT_SNAPSHOT)
    1242             :         {
    1243           2 :             if (IsTransactionBlock())
    1244           0 :                 ereport(ERROR,
    1245             :                 /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
    1246             :                         (errmsg("%s must not be called inside a transaction",
    1247             :                                 "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'export')")));
    1248             : 
    1249           2 :             need_full_snapshot = true;
    1250             :         }
    1251         660 :         else if (snapshot_action == CRS_USE_SNAPSHOT)
    1252             :         {
    1253         386 :             if (!IsTransactionBlock())
    1254           0 :                 ereport(ERROR,
    1255             :                 /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
    1256             :                         (errmsg("%s must be called inside a transaction",
    1257             :                                 "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'use')")));
    1258             : 
    1259         386 :             if (XactIsoLevel != XACT_REPEATABLE_READ)
    1260           0 :                 ereport(ERROR,
    1261             :                 /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
    1262             :                         (errmsg("%s must be called in REPEATABLE READ isolation mode transaction",
    1263             :                                 "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'use')")));
    1264         386 :             if (!XactReadOnly)
    1265           0 :                 ereport(ERROR,
    1266             :                 /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
    1267             :                         (errmsg("%s must be called in a read-only transaction",
    1268             :                                 "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'use')")));
    1269             : 
    1270         386 :             if (FirstSnapshotSet)
    1271           0 :                 ereport(ERROR,
    1272             :                 /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
    1273             :                         (errmsg("%s must be called before any query",
    1274             :                                 "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'use')")));
    1275             : 
    1276         386 :             if (IsSubTransaction())
    1277           0 :                 ereport(ERROR,
    1278             :                 /*- translator: %s is a CREATE_REPLICATION_SLOT statement */
    1279             :                         (errmsg("%s must not be called in a subtransaction",
    1280             :                                 "CREATE_REPLICATION_SLOT ... (SNAPSHOT 'use')")));
    1281             : 
    1282         386 :             need_full_snapshot = true;
    1283             :         }
    1284             : 
    1285         662 :         ctx = CreateInitDecodingContext(cmd->plugin, NIL, need_full_snapshot,
    1286             :                                         InvalidXLogRecPtr,
    1287         662 :                                         XL_ROUTINE(.page_read = logical_read_xlog_page,
    1288             :                                                    .segment_open = WalSndSegmentOpen,
    1289             :                                                    .segment_close = wal_segment_close),
    1290             :                                         WalSndPrepareWrite, WalSndWriteData,
    1291             :                                         WalSndUpdateProgress);
    1292             : 
    1293             :         /*
    1294             :          * Signal that we don't need the timeout mechanism. We're just
    1295             :          * creating the replication slot and don't yet accept feedback
    1296             :          * messages or send keepalives. As we possibly need to wait for
    1297             :          * further WAL the walsender would otherwise possibly be killed too
    1298             :          * soon.
    1299             :          */
    1300         662 :         last_reply_timestamp = 0;
    1301             : 
    1302             :         /* build initial snapshot, might take a while */
    1303         662 :         DecodingContextFindStartpoint(ctx);
    1304             : 
    1305             :         /*
    1306             :          * Export or use the snapshot if we've been asked to do so.
    1307             :          *
    1308             :          * NB. We will convert the snapbuild.c kind of snapshot to normal
    1309             :          * snapshot when doing this.
    1310             :          */
    1311         662 :         if (snapshot_action == CRS_EXPORT_SNAPSHOT)
    1312             :         {
    1313           2 :             snapshot_name = SnapBuildExportSnapshot(ctx->snapshot_builder);
    1314             :         }
    1315         660 :         else if (snapshot_action == CRS_USE_SNAPSHOT)
    1316             :         {
    1317             :             Snapshot    snap;
    1318             : 
    1319         386 :             snap = SnapBuildInitialSnapshot(ctx->snapshot_builder);
    1320         386 :             RestoreTransactionSnapshot(snap, MyProc);
    1321             :         }
    1322             : 
    1323             :         /* don't need the decoding context anymore */
    1324         662 :         FreeDecodingContext(ctx);
    1325             : 
    1326         662 :         if (!cmd->temporary)
    1327         662 :             ReplicationSlotPersist();
    1328             :     }
    1329             : 
    1330         932 :     snprintf(xloc, sizeof(xloc), "%X/%08X",
    1331         932 :              LSN_FORMAT_ARGS(MyReplicationSlot->data.confirmed_flush));
    1332             : 
    1333         932 :     dest = CreateDestReceiver(DestRemoteSimple);
    1334             : 
    1335             :     /*----------
    1336             :      * Need a tuple descriptor representing four columns:
    1337             :      * - first field: the slot name
    1338             :      * - second field: LSN at which we became consistent
    1339             :      * - third field: exported snapshot's name
    1340             :      * - fourth field: output plugin
    1341             :      */
    1342         932 :     tupdesc = CreateTemplateTupleDesc(4);
    1343         932 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 1, "slot_name",
    1344             :                               TEXTOID, -1, 0);
    1345         932 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 2, "consistent_point",
    1346             :                               TEXTOID, -1, 0);
    1347         932 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 3, "snapshot_name",
    1348             :                               TEXTOID, -1, 0);
    1349         932 :     TupleDescInitBuiltinEntry(tupdesc, (AttrNumber) 4, "output_plugin",
    1350             :                               TEXTOID, -1, 0);
    1351             : 
    1352             :     /* prepare for projection of tuples */
    1353         932 :     tstate = begin_tup_output_tupdesc(dest, tupdesc, &TTSOpsVirtual);
    1354             : 
    1355             :     /* slot_name */
    1356         932 :     slot_name = NameStr(MyReplicationSlot->data.name);
    1357         932 :     values[0] = CStringGetTextDatum(slot_name);
    1358             : 
    1359             :     /* consistent wal location */
    1360         932 :     values[1] = CStringGetTextDatum(xloc);
    1361             : 
    1362             :     /* snapshot name, or NULL if none */
    1363         932 :     if (snapshot_name != NULL)
    1364           2 :         values[2] = CStringGetTextDatum(snapshot_name);
    1365             :     else
    1366         930 :         nulls[2] = true;
    1367             : 
    1368             :     /* plugin, or NULL if none */
    1369         932 :     if (cmd->plugin != NULL)
    1370         662 :         values[3] = CStringGetTextDatum(cmd->plugin);
    1371             :     else
    1372         270 :         nulls[3] = true;
    1373             : 
    1374             :     /* send it to dest */
    1375         932 :     do_tup_output(tstate, values, nulls);
    1376         932 :     end_tup_output(tstate);
    1377             : 
    1378         932 :     ReplicationSlotRelease();
    1379         932 : }
    1380             : 
    1381             : /*
    1382             :  * Get rid of a replication slot that is no longer wanted.
    1383             :  */
    1384             : static void
    1385         534 : DropReplicationSlot(DropReplicationSlotCmd *cmd)
    1386             : {
    1387         534 :     ReplicationSlotDrop(cmd->slotname, !cmd->wait);
    1388         528 : }
    1389             : 
    1390             : /*
    1391             :  * Change the definition of a replication slot.
    1392             :  */
    1393             : static void
    1394          12 : AlterReplicationSlot(AlterReplicationSlotCmd *cmd)
    1395             : {
    1396          12 :     bool        failover_given = false;
    1397          12 :     bool        two_phase_given = false;
    1398             :     bool        failover;
    1399             :     bool        two_phase;
    1400             : 
    1401             :     /* Parse options */
    1402          36 :     foreach_ptr(DefElem, defel, cmd->options)
    1403             :     {
    1404          12 :         if (strcmp(defel->defname, "failover") == 0)
    1405             :         {
    1406          10 :             if (failover_given)
    1407           0 :                 ereport(ERROR,
    1408             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1409             :                          errmsg("conflicting or redundant options")));
    1410          10 :             failover_given = true;
    1411          10 :             failover = defGetBoolean(defel);
    1412             :         }
    1413           2 :         else if (strcmp(defel->defname, "two_phase") == 0)
    1414             :         {
    1415           2 :             if (two_phase_given)
    1416           0 :                 ereport(ERROR,
    1417             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1418             :                          errmsg("conflicting or redundant options")));
    1419           2 :             two_phase_given = true;
    1420           2 :             two_phase = defGetBoolean(defel);
    1421             :         }
    1422             :         else
    1423           0 :             elog(ERROR, "unrecognized option: %s", defel->defname);
    1424             :     }
    1425             : 
    1426          12 :     ReplicationSlotAlter(cmd->slotname,
    1427             :                          failover_given ? &failover : NULL,
    1428             :                          two_phase_given ? &two_phase : NULL);
    1429           8 : }
    1430             : 
    1431             : /*
    1432             :  * Load previously initiated logical slot and prepare for sending data (via
    1433             :  * WalSndLoop).
    1434             :  */
    1435             : static void
    1436         822 : StartLogicalReplication(StartReplicationCmd *cmd)
    1437             : {
    1438             :     StringInfoData buf;
    1439             :     QueryCompletion qc;
    1440             : 
    1441             :     /* make sure that our requirements are still fulfilled */
    1442         822 :     CheckLogicalDecodingRequirements();
    1443             : 
    1444             :     Assert(!MyReplicationSlot);
    1445             : 
    1446         818 :     ReplicationSlotAcquire(cmd->slotname, true, true);
    1447             : 
    1448             :     /*
    1449             :      * Force a disconnect, so that the decoding code doesn't need to care
    1450             :      * about an eventual switch from running in recovery, to running in a
    1451             :      * normal environment. Client code is expected to handle reconnects.
    1452             :      */
    1453         808 :     if (am_cascading_walsender && !RecoveryInProgress())
    1454             :     {
    1455           0 :         ereport(LOG,
    1456             :                 (errmsg("terminating walsender process after promotion")));
    1457           0 :         got_STOPPING = true;
    1458             :     }
    1459             : 
    1460             :     /*
    1461             :      * Create our decoding context, making it start at the previously ack'ed
    1462             :      * position.
    1463             :      *
    1464             :      * Do this before sending a CopyBothResponse message, so that any errors
    1465             :      * are reported early.
    1466             :      */
    1467         806 :     logical_decoding_ctx =
    1468         808 :         CreateDecodingContext(cmd->startpoint, cmd->options, false,
    1469         808 :                               XL_ROUTINE(.page_read = logical_read_xlog_page,
    1470             :                                          .segment_open = WalSndSegmentOpen,
    1471             :                                          .segment_close = wal_segment_close),
    1472             :                               WalSndPrepareWrite, WalSndWriteData,
    1473             :                               WalSndUpdateProgress);
    1474         806 :     xlogreader = logical_decoding_ctx->reader;
    1475             : 
    1476         806 :     WalSndSetState(WALSNDSTATE_CATCHUP);
    1477             : 
    1478             :     /* Send a CopyBothResponse message, and start streaming */
    1479         806 :     pq_beginmessage(&buf, PqMsg_CopyBothResponse);
    1480         806 :     pq_sendbyte(&buf, 0);
    1481         806 :     pq_sendint16(&buf, 0);
    1482         806 :     pq_endmessage(&buf);
    1483         806 :     pq_flush();
    1484             : 
    1485             :     /* Start reading WAL from the oldest required WAL. */
    1486         806 :     XLogBeginRead(logical_decoding_ctx->reader,
    1487         806 :                   MyReplicationSlot->data.restart_lsn);
    1488             : 
    1489             :     /*
    1490             :      * Report the location after which we'll send out further commits as the
    1491             :      * current sentPtr.
    1492             :      */
    1493         806 :     sentPtr = MyReplicationSlot->data.confirmed_flush;
    1494             : 
    1495             :     /* Also update the sent position status in shared memory */
    1496         806 :     SpinLockAcquire(&MyWalSnd->mutex);
    1497         806 :     MyWalSnd->sentPtr = MyReplicationSlot->data.restart_lsn;
    1498         806 :     SpinLockRelease(&MyWalSnd->mutex);
    1499             : 
    1500         806 :     replication_active = true;
    1501             : 
    1502         806 :     SyncRepInitConfig();
    1503             : 
    1504             :     /* Main loop of walsender */
    1505         806 :     WalSndLoop(XLogSendLogical);
    1506             : 
    1507         378 :     FreeDecodingContext(logical_decoding_ctx);
    1508         378 :     ReplicationSlotRelease();
    1509             : 
    1510         378 :     replication_active = false;
    1511         378 :     if (got_STOPPING)
    1512           0 :         proc_exit(0);
    1513         378 :     WalSndSetState(WALSNDSTATE_STARTUP);
    1514             : 
    1515             :     /* Get out of COPY mode (CommandComplete). */
    1516         378 :     SetQueryCompletion(&qc, CMDTAG_COPY, 0);
    1517         378 :     EndCommand(&qc, DestRemote, false);
    1518         378 : }
    1519             : 
    1520             : /*
    1521             :  * LogicalDecodingContext 'prepare_write' callback.
    1522             :  *
    1523             :  * Prepare a write into a StringInfo.
    1524             :  *
    1525             :  * Don't do anything lasting in here, it's quite possible that nothing will be done
    1526             :  * with the data.
    1527             :  */
    1528             : static void
    1529      369906 : WalSndPrepareWrite(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid, bool last_write)
    1530             : {
    1531             :     /* can't have sync rep confused by sending the same LSN several times */
    1532      369906 :     if (!last_write)
    1533         806 :         lsn = InvalidXLogRecPtr;
    1534             : 
    1535      369906 :     resetStringInfo(ctx->out);
    1536             : 
    1537      369906 :     pq_sendbyte(ctx->out, PqReplMsg_WALData);
    1538      369906 :     pq_sendint64(ctx->out, lsn); /* dataStart */
    1539      369906 :     pq_sendint64(ctx->out, lsn); /* walEnd */
    1540             : 
    1541             :     /*
    1542             :      * Fill out the sendtime later, just as it's done in XLogSendPhysical, but
    1543             :      * reserve space here.
    1544             :      */
    1545      369906 :     pq_sendint64(ctx->out, 0);   /* sendtime */
    1546      369906 : }
    1547             : 
    1548             : /*
    1549             :  * LogicalDecodingContext 'write' callback.
    1550             :  *
    1551             :  * Actually write out data previously prepared by WalSndPrepareWrite out to
    1552             :  * the network. Take as long as needed, but process replies from the other
    1553             :  * side and check timeouts during that.
    1554             :  */
    1555             : static void
    1556      369906 : WalSndWriteData(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid,
    1557             :                 bool last_write)
    1558             : {
    1559             :     TimestampTz now;
    1560             : 
    1561             :     /*
    1562             :      * Fill the send timestamp last, so that it is taken as late as possible.
    1563             :      * This is somewhat ugly, but the protocol is set as it's already used for
    1564             :      * several releases by streaming physical replication.
    1565             :      */
    1566      369906 :     resetStringInfo(&tmpbuf);
    1567      369906 :     now = GetCurrentTimestamp();
    1568      369906 :     pq_sendint64(&tmpbuf, now);
    1569      369906 :     memcpy(&ctx->out->data[1 + sizeof(int64) + sizeof(int64)],
    1570      369906 :            tmpbuf.data, sizeof(int64));
    1571             : 
    1572             :     /* output previously gathered data in a CopyData packet */
    1573      369906 :     pq_putmessage_noblock(PqMsg_CopyData, ctx->out->data, ctx->out->len);
    1574             : 
    1575      369906 :     CHECK_FOR_INTERRUPTS();
    1576             : 
    1577             :     /* Try to flush pending output to the client */
    1578      369906 :     if (pq_flush_if_writable() != 0)
    1579          58 :         WalSndShutdown();
    1580             : 
    1581             :     /* Try taking fast path unless we get too close to walsender timeout. */
    1582      369848 :     if (now < TimestampTzPlusMilliseconds(last_reply_timestamp,
    1583      369848 :                                           wal_sender_timeout / 2) &&
    1584      369848 :         !pq_is_send_pending())
    1585             :     {
    1586      369172 :         return;
    1587             :     }
    1588             : 
    1589             :     /* If we have pending write here, go to slow path */
    1590         676 :     ProcessPendingWrites();
    1591             : }
    1592             : 
    1593             : /*
    1594             :  * Wait until there is no pending write. Also process replies from the other
    1595             :  * side and check timeouts during that.
    1596             :  */
    1597             : static void
    1598         676 : ProcessPendingWrites(void)
    1599             : {
    1600             :     for (;;)
    1601         814 :     {
    1602             :         long        sleeptime;
    1603             : 
    1604             :         /* Check for input from the client */
    1605        1490 :         ProcessRepliesIfAny();
    1606             : 
    1607             :         /* die if timeout was reached */
    1608        1490 :         WalSndCheckTimeOut();
    1609             : 
    1610             :         /* Send keepalive if the time has come */
    1611        1490 :         WalSndKeepaliveIfNecessary();
    1612             : 
    1613        1490 :         if (!pq_is_send_pending())
    1614         676 :             break;
    1615             : 
    1616         814 :         sleeptime = WalSndComputeSleeptime(GetCurrentTimestamp());
    1617             : 
    1618             :         /* Sleep until something happens or we time out */
    1619         814 :         WalSndWait(WL_SOCKET_WRITEABLE | WL_SOCKET_READABLE, sleeptime,
    1620             :                    WAIT_EVENT_WAL_SENDER_WRITE_DATA);
    1621             : 
    1622             :         /* Clear any already-pending wakeups */
    1623         814 :         ResetLatch(MyLatch);
    1624             : 
    1625         814 :         CHECK_FOR_INTERRUPTS();
    1626             : 
    1627             :         /* Process any requests or signals received recently */
    1628         814 :         if (ConfigReloadPending)
    1629             :         {
    1630           0 :             ConfigReloadPending = false;
    1631           0 :             ProcessConfigFile(PGC_SIGHUP);
    1632           0 :             SyncRepInitConfig();
    1633             :         }
    1634             : 
    1635             :         /* Try to flush pending output to the client */
    1636         814 :         if (pq_flush_if_writable() != 0)
    1637           0 :             WalSndShutdown();
    1638             :     }
    1639             : 
    1640             :     /* reactivate latch so WalSndLoop knows to continue */
    1641         676 :     SetLatch(MyLatch);
    1642         676 : }
    1643             : 
    1644             : /*
    1645             :  * LogicalDecodingContext 'update_progress' callback.
    1646             :  *
    1647             :  * Write the current position to the lag tracker (see XLogSendPhysical).
    1648             :  *
    1649             :  * When skipping empty transactions, send a keepalive message if necessary.
    1650             :  */
    1651             : static void
    1652        4866 : WalSndUpdateProgress(LogicalDecodingContext *ctx, XLogRecPtr lsn, TransactionId xid,
    1653             :                      bool skipped_xact)
    1654             : {
    1655             :     static TimestampTz sendTime = 0;
    1656        4866 :     TimestampTz now = GetCurrentTimestamp();
    1657        4866 :     bool        pending_writes = false;
    1658        4866 :     bool        end_xact = ctx->end_xact;
    1659             : 
    1660             :     /*
    1661             :      * Track lag no more than once per WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS to
    1662             :      * avoid flooding the lag tracker when we commit frequently.
    1663             :      *
    1664             :      * We don't have a mechanism to get the ack for any LSN other than end
    1665             :      * xact LSN from the downstream. So, we track lag only for end of
    1666             :      * transaction LSN.
    1667             :      */
    1668             : #define WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS    1000
    1669        4866 :     if (end_xact && TimestampDifferenceExceeds(sendTime, now,
    1670             :                                                WALSND_LOGICAL_LAG_TRACK_INTERVAL_MS))
    1671             :     {
    1672         544 :         LagTrackerWrite(lsn, now);
    1673         544 :         sendTime = now;
    1674             :     }
    1675             : 
    1676             :     /*
    1677             :      * When skipping empty transactions in synchronous replication, we send a
    1678             :      * keepalive message to avoid delaying such transactions.
    1679             :      *
    1680             :      * It is okay to check sync_standbys_status without lock here as in the
    1681             :      * worst case we will just send an extra keepalive message when it is
    1682             :      * really not required.
    1683             :      */
    1684        4866 :     if (skipped_xact &&
    1685         702 :         SyncRepRequested() &&
    1686         702 :         (((volatile WalSndCtlData *) WalSndCtl)->sync_standbys_status & SYNC_STANDBY_DEFINED))
    1687             :     {
    1688           0 :         WalSndKeepalive(false, lsn);
    1689             : 
    1690             :         /* Try to flush pending output to the client */
    1691           0 :         if (pq_flush_if_writable() != 0)
    1692           0 :             WalSndShutdown();
    1693             : 
    1694             :         /* If we have pending write here, make sure it's actually flushed */
    1695           0 :         if (pq_is_send_pending())
    1696           0 :             pending_writes = true;
    1697             :     }
    1698             : 
    1699             :     /*
    1700             :      * Process pending writes if any or try to send a keepalive if required.
    1701             :      * We don't need to try sending keep alive messages at the transaction end
    1702             :      * as that will be done at a later point in time. This is required only
    1703             :      * for large transactions where we don't send any changes to the
    1704             :      * downstream and the receiver can timeout due to that.
    1705             :      */
    1706        4866 :     if (pending_writes || (!end_xact &&
    1707        3080 :                            now >= TimestampTzPlusMilliseconds(last_reply_timestamp,
    1708             :                                                               wal_sender_timeout / 2)))
    1709           0 :         ProcessPendingWrites();
    1710        4866 : }
    1711             : 
    1712             : /*
    1713             :  * Wake up the logical walsender processes with logical failover slots if the
    1714             :  * currently acquired physical slot is specified in synchronized_standby_slots GUC.
    1715             :  */
    1716             : void
    1717       59480 : PhysicalWakeupLogicalWalSnd(void)
    1718             : {
    1719             :     Assert(MyReplicationSlot && SlotIsPhysical(MyReplicationSlot));
    1720             : 
    1721             :     /*
    1722             :      * If we are running in a standby, there is no need to wake up walsenders.
    1723             :      * This is because we do not support syncing slots to cascading standbys,
    1724             :      * so, there are no walsenders waiting for standbys to catch up.
    1725             :      */
    1726       59480 :     if (RecoveryInProgress())
    1727         106 :         return;
    1728             : 
    1729       59374 :     if (SlotExistsInSyncStandbySlots(NameStr(MyReplicationSlot->data.name)))
    1730          14 :         ConditionVariableBroadcast(&WalSndCtl->wal_confirm_rcv_cv);
    1731             : }
    1732             : 
    1733             : /*
    1734             :  * Returns true if not all standbys have caught up to the flushed position
    1735             :  * (flushed_lsn) when the current acquired slot is a logical failover
    1736             :  * slot and we are streaming; otherwise, returns false.
    1737             :  *
    1738             :  * If returning true, the function sets the appropriate wait event in
    1739             :  * wait_event; otherwise, wait_event is set to 0.
    1740             :  */
    1741             : static bool
    1742       31914 : NeedToWaitForStandbys(XLogRecPtr flushed_lsn, uint32 *wait_event)
    1743             : {
    1744       31914 :     int         elevel = got_STOPPING ? ERROR : WARNING;
    1745             :     bool        failover_slot;
    1746             : 
    1747       31914 :     failover_slot = (replication_active && MyReplicationSlot->data.failover);
    1748             : 
    1749             :     /*
    1750             :      * Note that after receiving the shutdown signal, an ERROR is reported if
    1751             :      * any slots are dropped, invalidated, or inactive. This measure is taken
    1752             :      * to prevent the walsender from waiting indefinitely.
    1753             :      */
    1754       31914 :     if (failover_slot && !StandbySlotsHaveCaughtup(flushed_lsn, elevel))
    1755             :     {
    1756          10 :         *wait_event = WAIT_EVENT_WAIT_FOR_STANDBY_CONFIRMATION;
    1757          10 :         return true;
    1758             :     }
    1759             : 
    1760       31904 :     *wait_event = 0;
    1761       31904 :     return false;
    1762             : }
    1763             : 
    1764             : /*
    1765             :  * Returns true if we need to wait for WALs to be flushed to disk, or if not
    1766             :  * all standbys have caught up to the flushed position (flushed_lsn) when the
    1767             :  * current acquired slot is a logical failover slot and we are
    1768             :  * streaming; otherwise, returns false.
    1769             :  *
    1770             :  * If returning true, the function sets the appropriate wait event in
    1771             :  * wait_event; otherwise, wait_event is set to 0.
    1772             :  */
    1773             : static bool
    1774       43290 : NeedToWaitForWal(XLogRecPtr target_lsn, XLogRecPtr flushed_lsn,
    1775             :                  uint32 *wait_event)
    1776             : {
    1777             :     /* Check if we need to wait for WALs to be flushed to disk */
    1778       43290 :     if (target_lsn > flushed_lsn)
    1779             :     {
    1780       18384 :         *wait_event = WAIT_EVENT_WAL_SENDER_WAIT_FOR_WAL;
    1781       18384 :         return true;
    1782             :     }
    1783             : 
    1784             :     /* Check if the standby slots have caught up to the flushed position */
    1785       24906 :     return NeedToWaitForStandbys(flushed_lsn, wait_event);
    1786             : }
    1787             : 
    1788             : /*
    1789             :  * Wait till WAL < loc is flushed to disk so it can be safely sent to client.
    1790             :  *
    1791             :  * If the walsender holds a logical failover slot, we also wait for all the
    1792             :  * specified streaming replication standby servers to confirm receipt of WAL
    1793             :  * up to RecentFlushPtr. It is beneficial to wait here for the confirmation
    1794             :  * up to RecentFlushPtr rather than waiting before transmitting each change
    1795             :  * to logical subscribers, which is already covered by RecentFlushPtr.
    1796             :  *
    1797             :  * Returns end LSN of flushed WAL.  Normally this will be >= loc, but if we
    1798             :  * detect a shutdown request (either from postmaster or client) we will return
    1799             :  * early, so caller must always check.
    1800             :  */
    1801             : static XLogRecPtr
    1802       32392 : WalSndWaitForWal(XLogRecPtr loc)
    1803             : {
    1804             :     int         wakeEvents;
    1805       32392 :     uint32      wait_event = 0;
    1806             :     static XLogRecPtr RecentFlushPtr = InvalidXLogRecPtr;
    1807       32392 :     TimestampTz last_flush = 0;
    1808             : 
    1809             :     /*
    1810             :      * Fast path to avoid acquiring the spinlock in case we already know we
    1811             :      * have enough WAL available and all the standby servers have confirmed
    1812             :      * receipt of WAL up to RecentFlushPtr. This is particularly interesting
    1813             :      * if we're far behind.
    1814             :      */
    1815       32392 :     if (!XLogRecPtrIsInvalid(RecentFlushPtr) &&
    1816       31290 :         !NeedToWaitForWal(loc, RecentFlushPtr, &wait_event))
    1817       21188 :         return RecentFlushPtr;
    1818             : 
    1819             :     /*
    1820             :      * Within the loop, we wait for the necessary WALs to be flushed to disk
    1821             :      * first, followed by waiting for standbys to catch up if there are enough
    1822             :      * WALs (see NeedToWaitForWal()) or upon receiving the shutdown signal.
    1823             :      */
    1824             :     for (;;)
    1825        8146 :     {
    1826       19350 :         bool        wait_for_standby_at_stop = false;
    1827             :         long        sleeptime;
    1828             :         TimestampTz now;
    1829             : 
    1830             :         /* Clear any already-pending wakeups */
    1831       19350 :         ResetLatch(MyLatch);
    1832             : 
    1833       19350 :         CHECK_FOR_INTERRUPTS();
    1834             : 
    1835             :         /* Process any requests or signals received recently */
    1836       19338 :         if (ConfigReloadPending)
    1837             :         {
    1838          14 :             ConfigReloadPending = false;
    1839          14 :             ProcessConfigFile(PGC_SIGHUP);
    1840          14 :             SyncRepInitConfig();
    1841             :         }
    1842             : 
    1843             :         /* Check for input from the client */
    1844       19338 :         ProcessRepliesIfAny();
    1845             : 
    1846             :         /*
    1847             :          * If we're shutting down, trigger pending WAL to be written out,
    1848             :          * otherwise we'd possibly end up waiting for WAL that never gets
    1849             :          * written, because walwriter has shut down already.
    1850             :          */
    1851       19008 :         if (got_STOPPING)
    1852        7008 :             XLogBackgroundFlush();
    1853             : 
    1854             :         /*
    1855             :          * To avoid the scenario where standbys need to catch up to a newer
    1856             :          * WAL location in each iteration, we update our idea of the currently
    1857             :          * flushed position only if we are not waiting for standbys to catch
    1858             :          * up.
    1859             :          */
    1860       19008 :         if (wait_event != WAIT_EVENT_WAIT_FOR_STANDBY_CONFIRMATION)
    1861             :         {
    1862       18998 :             if (!RecoveryInProgress())
    1863       17244 :                 RecentFlushPtr = GetFlushRecPtr(NULL);
    1864             :             else
    1865        1754 :                 RecentFlushPtr = GetXLogReplayRecPtr(NULL);
    1866             :         }
    1867             : 
    1868             :         /*
    1869             :          * If postmaster asked us to stop and the standby slots have caught up
    1870             :          * to the flushed position, don't wait anymore.
    1871             :          *
    1872             :          * It's important to do this check after the recomputation of
    1873             :          * RecentFlushPtr, so we can send all remaining data before shutting
    1874             :          * down.
    1875             :          */
    1876       19008 :         if (got_STOPPING)
    1877             :         {
    1878        7008 :             if (NeedToWaitForStandbys(RecentFlushPtr, &wait_event))
    1879           0 :                 wait_for_standby_at_stop = true;
    1880             :             else
    1881        7008 :                 break;
    1882             :         }
    1883             : 
    1884             :         /*
    1885             :          * We only send regular messages to the client for full decoded
    1886             :          * transactions, but a synchronous replication and walsender shutdown
    1887             :          * possibly are waiting for a later location. So, before sleeping, we
    1888             :          * send a ping containing the flush location. If the receiver is
    1889             :          * otherwise idle, this keepalive will trigger a reply. Processing the
    1890             :          * reply will update these MyWalSnd locations.
    1891             :          */
    1892       12000 :         if (MyWalSnd->flush < sentPtr &&
    1893        5972 :             MyWalSnd->write < sentPtr &&
    1894        3480 :             !waiting_for_ping_response)
    1895        3480 :             WalSndKeepalive(false, InvalidXLogRecPtr);
    1896             : 
    1897             :         /*
    1898             :          * Exit the loop if already caught up and doesn't need to wait for
    1899             :          * standby slots.
    1900             :          */
    1901       12000 :         if (!wait_for_standby_at_stop &&
    1902       12000 :             !NeedToWaitForWal(loc, RecentFlushPtr, &wait_event))
    1903        3708 :             break;
    1904             : 
    1905             :         /*
    1906             :          * Waiting for new WAL or waiting for standbys to catch up. Since we
    1907             :          * need to wait, we're now caught up.
    1908             :          */
    1909        8292 :         WalSndCaughtUp = true;
    1910             : 
    1911             :         /*
    1912             :          * Try to flush any pending output to the client.
    1913             :          */
    1914        8292 :         if (pq_flush_if_writable() != 0)
    1915           0 :             WalSndShutdown();
    1916             : 
    1917             :         /*
    1918             :          * If we have received CopyDone from the client, sent CopyDone
    1919             :          * ourselves, and the output buffer is empty, it's time to exit
    1920             :          * streaming, so fail the current WAL fetch request.
    1921             :          */
    1922        8292 :         if (streamingDoneReceiving && streamingDoneSending &&
    1923         146 :             !pq_is_send_pending())
    1924         146 :             break;
    1925             : 
    1926             :         /* die if timeout was reached */
    1927        8146 :         WalSndCheckTimeOut();
    1928             : 
    1929             :         /* Send keepalive if the time has come */
    1930        8146 :         WalSndKeepaliveIfNecessary();
    1931             : 
    1932             :         /*
    1933             :          * Sleep until something happens or we time out.  Also wait for the
    1934             :          * socket becoming writable, if there's still pending output.
    1935             :          * Otherwise we might sit on sendable output data while waiting for
    1936             :          * new WAL to be generated.  (But if we have nothing to send, we don't
    1937             :          * want to wake on socket-writable.)
    1938             :          */
    1939        8146 :         now = GetCurrentTimestamp();
    1940        8146 :         sleeptime = WalSndComputeSleeptime(now);
    1941             : 
    1942        8146 :         wakeEvents = WL_SOCKET_READABLE;
    1943             : 
    1944        8146 :         if (pq_is_send_pending())
    1945           0 :             wakeEvents |= WL_SOCKET_WRITEABLE;
    1946             : 
    1947             :         Assert(wait_event != 0);
    1948             : 
    1949             :         /* Report IO statistics, if needed */
    1950        8146 :         if (TimestampDifferenceExceeds(last_flush, now,
    1951             :                                        WALSENDER_STATS_FLUSH_INTERVAL))
    1952             :         {
    1953        2896 :             pgstat_flush_io(false);
    1954        2896 :             (void) pgstat_flush_backend(false, PGSTAT_BACKEND_FLUSH_IO);
    1955        2896 :             last_flush = now;
    1956             :         }
    1957             : 
    1958        8146 :         WalSndWait(wakeEvents, sleeptime, wait_event);
    1959             :     }
    1960             : 
    1961             :     /* reactivate latch so WalSndLoop knows to continue */
    1962       10862 :     SetLatch(MyLatch);
    1963       10862 :     return RecentFlushPtr;
    1964             : }
    1965             : 
    1966             : /*
    1967             :  * Execute an incoming replication command.
    1968             :  *
    1969             :  * Returns true if the cmd_string was recognized as WalSender command, false
    1970             :  * if not.
    1971             :  */
    1972             : bool
    1973       10402 : exec_replication_command(const char *cmd_string)
    1974             : {
    1975             :     yyscan_t    scanner;
    1976             :     int         parse_rc;
    1977             :     Node       *cmd_node;
    1978             :     const char *cmdtag;
    1979       10402 :     MemoryContext old_context = CurrentMemoryContext;
    1980             : 
    1981             :     /* We save and re-use the cmd_context across calls */
    1982             :     static MemoryContext cmd_context = NULL;
    1983             : 
    1984             :     /*
    1985             :      * If WAL sender has been told that shutdown is getting close, switch its
    1986             :      * status accordingly to handle the next replication commands correctly.
    1987             :      */
    1988       10402 :     if (got_STOPPING)
    1989           0 :         WalSndSetState(WALSNDSTATE_STOPPING);
    1990             : 
    1991             :     /*
    1992             :      * Throw error if in stopping mode.  We need prevent commands that could
    1993             :      * generate WAL while the shutdown checkpoint is being written.  To be
    1994             :      * safe, we just prohibit all new commands.
    1995             :      */
    1996       10402 :     if (MyWalSnd->state == WALSNDSTATE_STOPPING)
    1997           0 :         ereport(ERROR,
    1998             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1999             :                  errmsg("cannot execute new commands while WAL sender is in stopping mode")));
    2000             : 
    2001             :     /*
    2002             :      * CREATE_REPLICATION_SLOT ... LOGICAL exports a snapshot until the next
    2003             :      * command arrives. Clean up the old stuff if there's anything.
    2004             :      */
    2005       10402 :     SnapBuildClearExportedSnapshot();
    2006             : 
    2007       10402 :     CHECK_FOR_INTERRUPTS();
    2008             : 
    2009             :     /*
    2010             :      * Prepare to parse and execute the command.
    2011             :      *
    2012             :      * Because replication command execution can involve beginning or ending
    2013             :      * transactions, we need a working context that will survive that, so we
    2014             :      * make it a child of TopMemoryContext.  That in turn creates a hazard of
    2015             :      * long-lived memory leaks if we lose track of the working context.  We
    2016             :      * deal with that by creating it only once per walsender, and resetting it
    2017             :      * for each new command.  (Normally this reset is a no-op, but if the
    2018             :      * prior exec_replication_command call failed with an error, it won't be.)
    2019             :      *
    2020             :      * This is subtler than it looks.  The transactions we manage can extend
    2021             :      * across replication commands, indeed SnapBuildClearExportedSnapshot
    2022             :      * might have just ended one.  Because transaction exit will revert to the
    2023             :      * memory context that was current at transaction start, we need to be
    2024             :      * sure that that context is still valid.  That motivates re-using the
    2025             :      * same cmd_context rather than making a new one each time.
    2026             :      */
    2027       10402 :     if (cmd_context == NULL)
    2028        2278 :         cmd_context = AllocSetContextCreate(TopMemoryContext,
    2029             :                                             "Replication command context",
    2030             :                                             ALLOCSET_DEFAULT_SIZES);
    2031             :     else
    2032        8124 :         MemoryContextReset(cmd_context);
    2033             : 
    2034       10402 :     MemoryContextSwitchTo(cmd_context);
    2035             : 
    2036       10402 :     replication_scanner_init(cmd_string, &scanner);
    2037             : 
    2038             :     /*
    2039             :      * Is it a WalSender command?
    2040             :      */
    2041       10402 :     if (!replication_scanner_is_replication_command(scanner))
    2042             :     {
    2043             :         /* Nope; clean up and get out. */
    2044        4626 :         replication_scanner_finish(scanner);
    2045             : 
    2046        4626 :         MemoryContextSwitchTo(old_context);
    2047        4626 :         MemoryContextReset(cmd_context);
    2048             : 
    2049             :         /* XXX this is a pretty random place to make this check */
    2050        4626 :         if (MyDatabaseId == InvalidOid)
    2051           0 :             ereport(ERROR,
    2052             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2053             :                      errmsg("cannot execute SQL commands in WAL sender for physical replication")));
    2054             : 
    2055             :         /* Tell the caller that this wasn't a WalSender command. */
    2056        4626 :         return false;
    2057             :     }
    2058             : 
    2059             :     /*
    2060             :      * Looks like a WalSender command, so parse it.
    2061             :      */
    2062        5776 :     parse_rc = replication_yyparse(&cmd_node, scanner);
    2063        5776 :     if (parse_rc != 0)
    2064           0 :         ereport(ERROR,
    2065             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2066             :                  errmsg_internal("replication command parser returned %d",
    2067             :                                  parse_rc)));
    2068        5776 :     replication_scanner_finish(scanner);
    2069             : 
    2070             :     /*
    2071             :      * Report query to various monitoring facilities.  For this purpose, we
    2072             :      * report replication commands just like SQL commands.
    2073             :      */
    2074        5776 :     debug_query_string = cmd_string;
    2075             : 
    2076        5776 :     pgstat_report_activity(STATE_RUNNING, cmd_string);
    2077             : 
    2078             :     /*
    2079             :      * Log replication command if log_replication_commands is enabled. Even
    2080             :      * when it's disabled, log the command with DEBUG1 level for backward
    2081             :      * compatibility.
    2082             :      */
    2083        5776 :     ereport(log_replication_commands ? LOG : DEBUG1,
    2084             :             (errmsg("received replication command: %s", cmd_string)));
    2085             : 
    2086             :     /*
    2087             :      * Disallow replication commands in aborted transaction blocks.
    2088             :      */
    2089        5776 :     if (IsAbortedTransactionBlockState())
    2090           0 :         ereport(ERROR,
    2091             :                 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
    2092             :                  errmsg("current transaction is aborted, "
    2093             :                         "commands ignored until end of transaction block")));
    2094             : 
    2095        5776 :     CHECK_FOR_INTERRUPTS();
    2096             : 
    2097             :     /*
    2098             :      * Allocate buffers that will be used for each outgoing and incoming
    2099             :      * message.  We do this just once per command to reduce palloc overhead.
    2100             :      */
    2101        5776 :     initStringInfo(&output_message);
    2102        5776 :     initStringInfo(&reply_message);
    2103        5776 :     initStringInfo(&tmpbuf);
    2104             : 
    2105        5776 :     switch (cmd_node->type)
    2106             :     {
    2107        1412 :         case T_IdentifySystemCmd:
    2108        1412 :             cmdtag = "IDENTIFY_SYSTEM";
    2109        1412 :             set_ps_display(cmdtag);
    2110        1412 :             IdentifySystem();
    2111        1412 :             EndReplicationCommand(cmdtag);
    2112        1412 :             break;
    2113             : 
    2114          12 :         case T_ReadReplicationSlotCmd:
    2115          12 :             cmdtag = "READ_REPLICATION_SLOT";
    2116          12 :             set_ps_display(cmdtag);
    2117          12 :             ReadReplicationSlot((ReadReplicationSlotCmd *) cmd_node);
    2118          10 :             EndReplicationCommand(cmdtag);
    2119          10 :             break;
    2120             : 
    2121         356 :         case T_BaseBackupCmd:
    2122         356 :             cmdtag = "BASE_BACKUP";
    2123         356 :             set_ps_display(cmdtag);
    2124         356 :             PreventInTransactionBlock(true, cmdtag);
    2125         356 :             SendBaseBackup((BaseBackupCmd *) cmd_node, uploaded_manifest);
    2126         304 :             EndReplicationCommand(cmdtag);
    2127         304 :             break;
    2128             : 
    2129         934 :         case T_CreateReplicationSlotCmd:
    2130         934 :             cmdtag = "CREATE_REPLICATION_SLOT";
    2131         934 :             set_ps_display(cmdtag);
    2132         934 :             CreateReplicationSlot((CreateReplicationSlotCmd *) cmd_node);
    2133         932 :             EndReplicationCommand(cmdtag);
    2134         932 :             break;
    2135             : 
    2136         534 :         case T_DropReplicationSlotCmd:
    2137         534 :             cmdtag = "DROP_REPLICATION_SLOT";
    2138         534 :             set_ps_display(cmdtag);
    2139         534 :             DropReplicationSlot((DropReplicationSlotCmd *) cmd_node);
    2140         528 :             EndReplicationCommand(cmdtag);
    2141         528 :             break;
    2142             : 
    2143          12 :         case T_AlterReplicationSlotCmd:
    2144          12 :             cmdtag = "ALTER_REPLICATION_SLOT";
    2145          12 :             set_ps_display(cmdtag);
    2146          12 :             AlterReplicationSlot((AlterReplicationSlotCmd *) cmd_node);
    2147           8 :             EndReplicationCommand(cmdtag);
    2148           8 :             break;
    2149             : 
    2150        1342 :         case T_StartReplicationCmd:
    2151             :             {
    2152        1342 :                 StartReplicationCmd *cmd = (StartReplicationCmd *) cmd_node;
    2153             : 
    2154        1342 :                 cmdtag = "START_REPLICATION";
    2155        1342 :                 set_ps_display(cmdtag);
    2156        1342 :                 PreventInTransactionBlock(true, cmdtag);
    2157             : 
    2158        1342 :                 if (cmd->kind == REPLICATION_KIND_PHYSICAL)
    2159         520 :                     StartReplication(cmd);
    2160             :                 else
    2161         822 :                     StartLogicalReplication(cmd);
    2162             : 
    2163             :                 /* dupe, but necessary per libpqrcv_endstreaming */
    2164         676 :                 EndReplicationCommand(cmdtag);
    2165             : 
    2166             :                 Assert(xlogreader != NULL);
    2167         676 :                 break;
    2168             :             }
    2169             : 
    2170          28 :         case T_TimeLineHistoryCmd:
    2171          28 :             cmdtag = "TIMELINE_HISTORY";
    2172          28 :             set_ps_display(cmdtag);
    2173          28 :             PreventInTransactionBlock(true, cmdtag);
    2174          28 :             SendTimeLineHistory((TimeLineHistoryCmd *) cmd_node);
    2175          28 :             EndReplicationCommand(cmdtag);
    2176          28 :             break;
    2177             : 
    2178        1124 :         case T_VariableShowStmt:
    2179             :             {
    2180        1124 :                 DestReceiver *dest = CreateDestReceiver(DestRemoteSimple);
    2181        1124 :                 VariableShowStmt *n = (VariableShowStmt *) cmd_node;
    2182             : 
    2183        1124 :                 cmdtag = "SHOW";
    2184        1124 :                 set_ps_display(cmdtag);
    2185             : 
    2186             :                 /* syscache access needs a transaction environment */
    2187        1124 :                 StartTransactionCommand();
    2188        1124 :                 GetPGVariable(n->name, dest);
    2189        1124 :                 CommitTransactionCommand();
    2190        1124 :                 EndReplicationCommand(cmdtag);
    2191             :             }
    2192        1124 :             break;
    2193             : 
    2194          22 :         case T_UploadManifestCmd:
    2195          22 :             cmdtag = "UPLOAD_MANIFEST";
    2196          22 :             set_ps_display(cmdtag);
    2197          22 :             PreventInTransactionBlock(true, cmdtag);
    2198          22 :             UploadManifest();
    2199          20 :             EndReplicationCommand(cmdtag);
    2200          20 :             break;
    2201             : 
    2202           0 :         default:
    2203           0 :             elog(ERROR, "unrecognized replication command node tag: %u",
    2204             :                  cmd_node->type);
    2205             :     }
    2206             : 
    2207             :     /*
    2208             :      * Done.  Revert to caller's memory context, and clean out the cmd_context
    2209             :      * to recover memory right away.
    2210             :      */
    2211        5042 :     MemoryContextSwitchTo(old_context);
    2212        5042 :     MemoryContextReset(cmd_context);
    2213             : 
    2214             :     /*
    2215             :      * We need not update ps display or pg_stat_activity, because PostgresMain
    2216             :      * will reset those to "idle".  But we must reset debug_query_string to
    2217             :      * ensure it doesn't become a dangling pointer.
    2218             :      */
    2219        5042 :     debug_query_string = NULL;
    2220             : 
    2221        5042 :     return true;
    2222             : }
    2223             : 
    2224             : /*
    2225             :  * Process any incoming messages while streaming. Also checks if the remote
    2226             :  * end has closed the connection.
    2227             :  */
    2228             : static void
    2229     1530162 : ProcessRepliesIfAny(void)
    2230             : {
    2231             :     unsigned char firstchar;
    2232             :     int         maxmsglen;
    2233             :     int         r;
    2234     1530162 :     bool        received = false;
    2235             : 
    2236     1530162 :     last_processing = GetCurrentTimestamp();
    2237             : 
    2238             :     /*
    2239             :      * If we already received a CopyDone from the frontend, any subsequent
    2240             :      * message is the beginning of a new command, and should be processed in
    2241             :      * the main processing loop.
    2242             :      */
    2243     3311302 :     while (!streamingDoneReceiving)
    2244             :     {
    2245     1779796 :         pq_startmsgread();
    2246     1779796 :         r = pq_getbyte_if_available(&firstchar);
    2247     1779796 :         if (r < 0)
    2248             :         {
    2249             :             /* unexpected error or EOF */
    2250          26 :             ereport(COMMERROR,
    2251             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    2252             :                      errmsg("unexpected EOF on standby connection")));
    2253          26 :             proc_exit(0);
    2254             :         }
    2255     1779770 :         if (r == 0)
    2256             :         {
    2257             :             /* no data available without blocking */
    2258     1528324 :             pq_endmsgread();
    2259     1528324 :             break;
    2260             :         }
    2261             : 
    2262             :         /* Validate message type and set packet size limit */
    2263      251446 :         switch (firstchar)
    2264             :         {
    2265      250302 :             case PqMsg_CopyData:
    2266      250302 :                 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
    2267      250302 :                 break;
    2268        1144 :             case PqMsg_CopyDone:
    2269             :             case PqMsg_Terminate:
    2270        1144 :                 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
    2271        1144 :                 break;
    2272           0 :             default:
    2273           0 :                 ereport(FATAL,
    2274             :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
    2275             :                          errmsg("invalid standby message type \"%c\"",
    2276             :                                 firstchar)));
    2277             :                 maxmsglen = 0;  /* keep compiler quiet */
    2278             :                 break;
    2279             :         }
    2280             : 
    2281             :         /* Read the message contents */
    2282      251446 :         resetStringInfo(&reply_message);
    2283      251446 :         if (pq_getmessage(&reply_message, maxmsglen))
    2284             :         {
    2285           0 :             ereport(COMMERROR,
    2286             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    2287             :                      errmsg("unexpected EOF on standby connection")));
    2288           0 :             proc_exit(0);
    2289             :         }
    2290             : 
    2291             :         /* ... and process it */
    2292      251446 :         switch (firstchar)
    2293             :         {
    2294             :                 /*
    2295             :                  * PqMsg_CopyData means a standby reply wrapped in a CopyData
    2296             :                  * packet.
    2297             :                  */
    2298      250302 :             case PqMsg_CopyData:
    2299      250302 :                 ProcessStandbyMessage();
    2300      250302 :                 received = true;
    2301      250302 :                 break;
    2302             : 
    2303             :                 /*
    2304             :                  * PqMsg_CopyDone means the standby requested to finish
    2305             :                  * streaming.  Reply with CopyDone, if we had not sent that
    2306             :                  * already.
    2307             :                  */
    2308         676 :             case PqMsg_CopyDone:
    2309         676 :                 if (!streamingDoneSending)
    2310             :                 {
    2311         650 :                     pq_putmessage_noblock(PqMsg_CopyDone, NULL, 0);
    2312         650 :                     streamingDoneSending = true;
    2313             :                 }
    2314             : 
    2315         676 :                 streamingDoneReceiving = true;
    2316         676 :                 received = true;
    2317         676 :                 break;
    2318             : 
    2319             :                 /*
    2320             :                  * PqMsg_Terminate means that the standby is closing down the
    2321             :                  * socket.
    2322             :                  */
    2323         468 :             case PqMsg_Terminate:
    2324         468 :                 proc_exit(0);
    2325             : 
    2326      250978 :             default:
    2327             :                 Assert(false);  /* NOT REACHED */
    2328             :         }
    2329             :     }
    2330             : 
    2331             :     /*
    2332             :      * Save the last reply timestamp if we've received at least one reply.
    2333             :      */
    2334     1529668 :     if (received)
    2335             :     {
    2336       84404 :         last_reply_timestamp = last_processing;
    2337       84404 :         waiting_for_ping_response = false;
    2338             :     }
    2339     1529668 : }
    2340             : 
    2341             : /*
    2342             :  * Process a status update message received from standby.
    2343             :  */
    2344             : static void
    2345      250302 : ProcessStandbyMessage(void)
    2346             : {
    2347             :     char        msgtype;
    2348             : 
    2349             :     /*
    2350             :      * Check message type from the first byte.
    2351             :      */
    2352      250302 :     msgtype = pq_getmsgbyte(&reply_message);
    2353             : 
    2354      250302 :     switch (msgtype)
    2355             :     {
    2356      247366 :         case PqReplMsg_StandbyStatusUpdate:
    2357      247366 :             ProcessStandbyReplyMessage();
    2358      247366 :             break;
    2359             : 
    2360         272 :         case PqReplMsg_HotStandbyFeedback:
    2361         272 :             ProcessStandbyHSFeedbackMessage();
    2362         272 :             break;
    2363             : 
    2364        2664 :         case PqReplMsg_PrimaryStatusRequest:
    2365        2664 :             ProcessStandbyPSRequestMessage();
    2366        2664 :             break;
    2367             : 
    2368           0 :         default:
    2369           0 :             ereport(COMMERROR,
    2370             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    2371             :                      errmsg("unexpected message type \"%c\"", msgtype)));
    2372           0 :             proc_exit(0);
    2373             :     }
    2374      250302 : }
    2375             : 
    2376             : /*
    2377             :  * Remember that a walreceiver just confirmed receipt of lsn `lsn`.
    2378             :  */
    2379             : static void
    2380      133326 : PhysicalConfirmReceivedLocation(XLogRecPtr lsn)
    2381             : {
    2382      133326 :     bool        changed = false;
    2383      133326 :     ReplicationSlot *slot = MyReplicationSlot;
    2384             : 
    2385             :     Assert(lsn != InvalidXLogRecPtr);
    2386      133326 :     SpinLockAcquire(&slot->mutex);
    2387      133326 :     if (slot->data.restart_lsn != lsn)
    2388             :     {
    2389       59466 :         changed = true;
    2390       59466 :         slot->data.restart_lsn = lsn;
    2391             :     }
    2392      133326 :     SpinLockRelease(&slot->mutex);
    2393             : 
    2394      133326 :     if (changed)
    2395             :     {
    2396       59466 :         ReplicationSlotMarkDirty();
    2397       59466 :         ReplicationSlotsComputeRequiredLSN();
    2398       59466 :         PhysicalWakeupLogicalWalSnd();
    2399             :     }
    2400             : 
    2401             :     /*
    2402             :      * One could argue that the slot should be saved to disk now, but that'd
    2403             :      * be energy wasted - the worst thing lost information could cause here is
    2404             :      * to give wrong information in a statistics view - we'll just potentially
    2405             :      * be more conservative in removing files.
    2406             :      */
    2407      133326 : }
    2408             : 
    2409             : /*
    2410             :  * Regular reply from standby advising of WAL locations on standby server.
    2411             :  */
    2412             : static void
    2413      247366 : ProcessStandbyReplyMessage(void)
    2414             : {
    2415             :     XLogRecPtr  writePtr,
    2416             :                 flushPtr,
    2417             :                 applyPtr;
    2418             :     bool        replyRequested;
    2419             :     TimeOffset  writeLag,
    2420             :                 flushLag,
    2421             :                 applyLag;
    2422             :     bool        clearLagTimes;
    2423             :     TimestampTz now;
    2424             :     TimestampTz replyTime;
    2425             : 
    2426             :     static bool fullyAppliedLastTime = false;
    2427             : 
    2428             :     /* the caller already consumed the msgtype byte */
    2429      247366 :     writePtr = pq_getmsgint64(&reply_message);
    2430      247366 :     flushPtr = pq_getmsgint64(&reply_message);
    2431      247366 :     applyPtr = pq_getmsgint64(&reply_message);
    2432      247366 :     replyTime = pq_getmsgint64(&reply_message);
    2433      247366 :     replyRequested = pq_getmsgbyte(&reply_message);
    2434             : 
    2435      247366 :     if (message_level_is_interesting(DEBUG2))
    2436             :     {
    2437             :         char       *replyTimeStr;
    2438             : 
    2439             :         /* Copy because timestamptz_to_str returns a static buffer */
    2440        1328 :         replyTimeStr = pstrdup(timestamptz_to_str(replyTime));
    2441             : 
    2442        1328 :         elog(DEBUG2, "write %X/%08X flush %X/%08X apply %X/%08X%s reply_time %s",
    2443             :              LSN_FORMAT_ARGS(writePtr),
    2444             :              LSN_FORMAT_ARGS(flushPtr),
    2445             :              LSN_FORMAT_ARGS(applyPtr),
    2446             :              replyRequested ? " (reply requested)" : "",
    2447             :              replyTimeStr);
    2448             : 
    2449        1328 :         pfree(replyTimeStr);
    2450             :     }
    2451             : 
    2452             :     /* See if we can compute the round-trip lag for these positions. */
    2453      247366 :     now = GetCurrentTimestamp();
    2454      247366 :     writeLag = LagTrackerRead(SYNC_REP_WAIT_WRITE, writePtr, now);
    2455      247366 :     flushLag = LagTrackerRead(SYNC_REP_WAIT_FLUSH, flushPtr, now);
    2456      247366 :     applyLag = LagTrackerRead(SYNC_REP_WAIT_APPLY, applyPtr, now);
    2457             : 
    2458             :     /*
    2459             :      * If the standby reports that it has fully replayed the WAL in two
    2460             :      * consecutive reply messages, then the second such message must result
    2461             :      * from wal_receiver_status_interval expiring on the standby.  This is a
    2462             :      * convenient time to forget the lag times measured when it last
    2463             :      * wrote/flushed/applied a WAL record, to avoid displaying stale lag data
    2464             :      * until more WAL traffic arrives.
    2465             :      */
    2466      247366 :     clearLagTimes = false;
    2467      247366 :     if (applyPtr == sentPtr)
    2468             :     {
    2469        9404 :         if (fullyAppliedLastTime)
    2470        2512 :             clearLagTimes = true;
    2471        9404 :         fullyAppliedLastTime = true;
    2472             :     }
    2473             :     else
    2474      237962 :         fullyAppliedLastTime = false;
    2475             : 
    2476             :     /* Send a reply if the standby requested one. */
    2477      247366 :     if (replyRequested)
    2478           0 :         WalSndKeepalive(false, InvalidXLogRecPtr);
    2479             : 
    2480             :     /*
    2481             :      * Update shared state for this WalSender process based on reply data from
    2482             :      * standby.
    2483             :      */
    2484             :     {
    2485      247366 :         WalSnd     *walsnd = MyWalSnd;
    2486             : 
    2487      247366 :         SpinLockAcquire(&walsnd->mutex);
    2488      247366 :         walsnd->write = writePtr;
    2489      247366 :         walsnd->flush = flushPtr;
    2490      247366 :         walsnd->apply = applyPtr;
    2491      247366 :         if (writeLag != -1 || clearLagTimes)
    2492      124556 :             walsnd->writeLag = writeLag;
    2493      247366 :         if (flushLag != -1 || clearLagTimes)
    2494      141768 :             walsnd->flushLag = flushLag;
    2495      247366 :         if (applyLag != -1 || clearLagTimes)
    2496      144468 :             walsnd->applyLag = applyLag;
    2497      247366 :         walsnd->replyTime = replyTime;
    2498      247366 :         SpinLockRelease(&walsnd->mutex);
    2499             :     }
    2500             : 
    2501      247366 :     if (!am_cascading_walsender)
    2502      246678 :         SyncRepReleaseWaiters();
    2503             : 
    2504             :     /*
    2505             :      * Advance our local xmin horizon when the client confirmed a flush.
    2506             :      */
    2507      247366 :     if (MyReplicationSlot && flushPtr != InvalidXLogRecPtr)
    2508             :     {
    2509      237586 :         if (SlotIsLogical(MyReplicationSlot))
    2510      104260 :             LogicalConfirmReceivedLocation(flushPtr);
    2511             :         else
    2512      133326 :             PhysicalConfirmReceivedLocation(flushPtr);
    2513             :     }
    2514      247366 : }
    2515             : 
    2516             : /* compute new replication slot xmin horizon if needed */
    2517             : static void
    2518         122 : PhysicalReplicationSlotNewXmin(TransactionId feedbackXmin, TransactionId feedbackCatalogXmin)
    2519             : {
    2520         122 :     bool        changed = false;
    2521         122 :     ReplicationSlot *slot = MyReplicationSlot;
    2522             : 
    2523         122 :     SpinLockAcquire(&slot->mutex);
    2524         122 :     MyProc->xmin = InvalidTransactionId;
    2525             : 
    2526             :     /*
    2527             :      * For physical replication we don't need the interlock provided by xmin
    2528             :      * and effective_xmin since the consequences of a missed increase are
    2529             :      * limited to query cancellations, so set both at once.
    2530             :      */
    2531         122 :     if (!TransactionIdIsNormal(slot->data.xmin) ||
    2532          60 :         !TransactionIdIsNormal(feedbackXmin) ||
    2533          60 :         TransactionIdPrecedes(slot->data.xmin, feedbackXmin))
    2534             :     {
    2535          80 :         changed = true;
    2536          80 :         slot->data.xmin = feedbackXmin;
    2537          80 :         slot->effective_xmin = feedbackXmin;
    2538             :     }
    2539         122 :     if (!TransactionIdIsNormal(slot->data.catalog_xmin) ||
    2540          30 :         !TransactionIdIsNormal(feedbackCatalogXmin) ||
    2541          30 :         TransactionIdPrecedes(slot->data.catalog_xmin, feedbackCatalogXmin))
    2542             :     {
    2543          94 :         changed = true;
    2544          94 :         slot->data.catalog_xmin = feedbackCatalogXmin;
    2545          94 :         slot->effective_catalog_xmin = feedbackCatalogXmin;
    2546             :     }
    2547         122 :     SpinLockRelease(&slot->mutex);
    2548             : 
    2549         122 :     if (changed)
    2550             :     {
    2551         100 :         ReplicationSlotMarkDirty();
    2552         100 :         ReplicationSlotsComputeRequiredXmin(false);
    2553             :     }
    2554         122 : }
    2555             : 
    2556             : /*
    2557             :  * Check that the provided xmin/epoch are sane, that is, not in the future
    2558             :  * and not so far back as to be already wrapped around.
    2559             :  *
    2560             :  * Epoch of nextXid should be same as standby, or if the counter has
    2561             :  * wrapped, then one greater than standby.
    2562             :  *
    2563             :  * This check doesn't care about whether clog exists for these xids
    2564             :  * at all.
    2565             :  */
    2566             : static bool
    2567         130 : TransactionIdInRecentPast(TransactionId xid, uint32 epoch)
    2568             : {
    2569             :     FullTransactionId nextFullXid;
    2570             :     TransactionId nextXid;
    2571             :     uint32      nextEpoch;
    2572             : 
    2573         130 :     nextFullXid = ReadNextFullTransactionId();
    2574         130 :     nextXid = XidFromFullTransactionId(nextFullXid);
    2575         130 :     nextEpoch = EpochFromFullTransactionId(nextFullXid);
    2576             : 
    2577         130 :     if (xid <= nextXid)
    2578             :     {
    2579         130 :         if (epoch != nextEpoch)
    2580           0 :             return false;
    2581             :     }
    2582             :     else
    2583             :     {
    2584           0 :         if (epoch + 1 != nextEpoch)
    2585           0 :             return false;
    2586             :     }
    2587             : 
    2588         130 :     if (!TransactionIdPrecedesOrEquals(xid, nextXid))
    2589           0 :         return false;           /* epoch OK, but it's wrapped around */
    2590             : 
    2591         130 :     return true;
    2592             : }
    2593             : 
    2594             : /*
    2595             :  * Hot Standby feedback
    2596             :  */
    2597             : static void
    2598         272 : ProcessStandbyHSFeedbackMessage(void)
    2599             : {
    2600             :     TransactionId feedbackXmin;
    2601             :     uint32      feedbackEpoch;
    2602             :     TransactionId feedbackCatalogXmin;
    2603             :     uint32      feedbackCatalogEpoch;
    2604             :     TimestampTz replyTime;
    2605             : 
    2606             :     /*
    2607             :      * Decipher the reply message. The caller already consumed the msgtype
    2608             :      * byte. See XLogWalRcvSendHSFeedback() in walreceiver.c for the creation
    2609             :      * of this message.
    2610             :      */
    2611         272 :     replyTime = pq_getmsgint64(&reply_message);
    2612         272 :     feedbackXmin = pq_getmsgint(&reply_message, 4);
    2613         272 :     feedbackEpoch = pq_getmsgint(&reply_message, 4);
    2614         272 :     feedbackCatalogXmin = pq_getmsgint(&reply_message, 4);
    2615         272 :     feedbackCatalogEpoch = pq_getmsgint(&reply_message, 4);
    2616             : 
    2617         272 :     if (message_level_is_interesting(DEBUG2))
    2618             :     {
    2619             :         char       *replyTimeStr;
    2620             : 
    2621             :         /* Copy because timestamptz_to_str returns a static buffer */
    2622           8 :         replyTimeStr = pstrdup(timestamptz_to_str(replyTime));
    2623             : 
    2624           8 :         elog(DEBUG2, "hot standby feedback xmin %u epoch %u, catalog_xmin %u epoch %u reply_time %s",
    2625             :              feedbackXmin,
    2626             :              feedbackEpoch,
    2627             :              feedbackCatalogXmin,
    2628             :              feedbackCatalogEpoch,
    2629             :              replyTimeStr);
    2630             : 
    2631           8 :         pfree(replyTimeStr);
    2632             :     }
    2633             : 
    2634             :     /*
    2635             :      * Update shared state for this WalSender process based on reply data from
    2636             :      * standby.
    2637             :      */
    2638             :     {
    2639         272 :         WalSnd     *walsnd = MyWalSnd;
    2640             : 
    2641         272 :         SpinLockAcquire(&walsnd->mutex);
    2642         272 :         walsnd->replyTime = replyTime;
    2643         272 :         SpinLockRelease(&walsnd->mutex);
    2644             :     }
    2645             : 
    2646             :     /*
    2647             :      * Unset WalSender's xmins if the feedback message values are invalid.
    2648             :      * This happens when the downstream turned hot_standby_feedback off.
    2649             :      */
    2650         272 :     if (!TransactionIdIsNormal(feedbackXmin)
    2651         184 :         && !TransactionIdIsNormal(feedbackCatalogXmin))
    2652             :     {
    2653         184 :         MyProc->xmin = InvalidTransactionId;
    2654         184 :         if (MyReplicationSlot != NULL)
    2655          42 :             PhysicalReplicationSlotNewXmin(feedbackXmin, feedbackCatalogXmin);
    2656         184 :         return;
    2657             :     }
    2658             : 
    2659             :     /*
    2660             :      * Check that the provided xmin/epoch are sane, that is, not in the future
    2661             :      * and not so far back as to be already wrapped around.  Ignore if not.
    2662             :      */
    2663          88 :     if (TransactionIdIsNormal(feedbackXmin) &&
    2664          88 :         !TransactionIdInRecentPast(feedbackXmin, feedbackEpoch))
    2665           0 :         return;
    2666             : 
    2667          88 :     if (TransactionIdIsNormal(feedbackCatalogXmin) &&
    2668          42 :         !TransactionIdInRecentPast(feedbackCatalogXmin, feedbackCatalogEpoch))
    2669           0 :         return;
    2670             : 
    2671             :     /*
    2672             :      * Set the WalSender's xmin equal to the standby's requested xmin, so that
    2673             :      * the xmin will be taken into account by GetSnapshotData() /
    2674             :      * ComputeXidHorizons().  This will hold back the removal of dead rows and
    2675             :      * thereby prevent the generation of cleanup conflicts on the standby
    2676             :      * server.
    2677             :      *
    2678             :      * There is a small window for a race condition here: although we just
    2679             :      * checked that feedbackXmin precedes nextXid, the nextXid could have
    2680             :      * gotten advanced between our fetching it and applying the xmin below,
    2681             :      * perhaps far enough to make feedbackXmin wrap around.  In that case the
    2682             :      * xmin we set here would be "in the future" and have no effect.  No point
    2683             :      * in worrying about this since it's too late to save the desired data
    2684             :      * anyway.  Assuming that the standby sends us an increasing sequence of
    2685             :      * xmins, this could only happen during the first reply cycle, else our
    2686             :      * own xmin would prevent nextXid from advancing so far.
    2687             :      *
    2688             :      * We don't bother taking the ProcArrayLock here.  Setting the xmin field
    2689             :      * is assumed atomic, and there's no real need to prevent concurrent
    2690             :      * horizon determinations.  (If we're moving our xmin forward, this is
    2691             :      * obviously safe, and if we're moving it backwards, well, the data is at
    2692             :      * risk already since a VACUUM could already have determined the horizon.)
    2693             :      *
    2694             :      * If we're using a replication slot we reserve the xmin via that,
    2695             :      * otherwise via the walsender's PGPROC entry. We can only track the
    2696             :      * catalog xmin separately when using a slot, so we store the least of the
    2697             :      * two provided when not using a slot.
    2698             :      *
    2699             :      * XXX: It might make sense to generalize the ephemeral slot concept and
    2700             :      * always use the slot mechanism to handle the feedback xmin.
    2701             :      */
    2702          88 :     if (MyReplicationSlot != NULL)  /* XXX: persistency configurable? */
    2703          80 :         PhysicalReplicationSlotNewXmin(feedbackXmin, feedbackCatalogXmin);
    2704             :     else
    2705             :     {
    2706           8 :         if (TransactionIdIsNormal(feedbackCatalogXmin)
    2707           0 :             && TransactionIdPrecedes(feedbackCatalogXmin, feedbackXmin))
    2708           0 :             MyProc->xmin = feedbackCatalogXmin;
    2709             :         else
    2710           8 :             MyProc->xmin = feedbackXmin;
    2711             :     }
    2712             : }
    2713             : 
    2714             : /*
    2715             :  * Process the request for a primary status update message.
    2716             :  */
    2717             : static void
    2718        2664 : ProcessStandbyPSRequestMessage(void)
    2719             : {
    2720        2664 :     XLogRecPtr  lsn = InvalidXLogRecPtr;
    2721             :     TransactionId oldestXidInCommit;
    2722             :     FullTransactionId nextFullXid;
    2723             :     FullTransactionId fullOldestXidInCommit;
    2724        2664 :     WalSnd     *walsnd = MyWalSnd;
    2725             :     TimestampTz replyTime;
    2726             : 
    2727             :     /*
    2728             :      * This shouldn't happen because we don't support getting primary status
    2729             :      * message from standby.
    2730             :      */
    2731        2664 :     if (RecoveryInProgress())
    2732           0 :         elog(ERROR, "the primary status is unavailable during recovery");
    2733             : 
    2734        2664 :     replyTime = pq_getmsgint64(&reply_message);
    2735             : 
    2736             :     /*
    2737             :      * Update shared state for this WalSender process based on reply data from
    2738             :      * standby.
    2739             :      */
    2740        2664 :     SpinLockAcquire(&walsnd->mutex);
    2741        2664 :     walsnd->replyTime = replyTime;
    2742        2664 :     SpinLockRelease(&walsnd->mutex);
    2743             : 
    2744             :     /*
    2745             :      * Consider transactions in the current database, as only these are the
    2746             :      * ones replicated.
    2747             :      */
    2748        2664 :     oldestXidInCommit = GetOldestActiveTransactionId(true, false);
    2749        2664 :     nextFullXid = ReadNextFullTransactionId();
    2750        2664 :     fullOldestXidInCommit = FullTransactionIdFromAllowableAt(nextFullXid,
    2751             :                                                              oldestXidInCommit);
    2752        2664 :     lsn = GetXLogWriteRecPtr();
    2753             : 
    2754        2664 :     elog(DEBUG2, "sending primary status");
    2755             : 
    2756             :     /* construct the message... */
    2757        2664 :     resetStringInfo(&output_message);
    2758        2664 :     pq_sendbyte(&output_message, PqReplMsg_PrimaryStatusUpdate);
    2759        2664 :     pq_sendint64(&output_message, lsn);
    2760        2664 :     pq_sendint64(&output_message, (int64) U64FromFullTransactionId(fullOldestXidInCommit));
    2761        2664 :     pq_sendint64(&output_message, (int64) U64FromFullTransactionId(nextFullXid));
    2762        2664 :     pq_sendint64(&output_message, GetCurrentTimestamp());
    2763             : 
    2764             :     /* ... and send it wrapped in CopyData */
    2765        2664 :     pq_putmessage_noblock(PqMsg_CopyData, output_message.data, output_message.len);
    2766        2664 : }
    2767             : 
    2768             : /*
    2769             :  * Compute how long send/receive loops should sleep.
    2770             :  *
    2771             :  * If wal_sender_timeout is enabled we want to wake up in time to send
    2772             :  * keepalives and to abort the connection if wal_sender_timeout has been
    2773             :  * reached.
    2774             :  */
    2775             : static long
    2776      126342 : WalSndComputeSleeptime(TimestampTz now)
    2777             : {
    2778      126342 :     long        sleeptime = 10000;  /* 10 s */
    2779             : 
    2780      126342 :     if (wal_sender_timeout > 0 && last_reply_timestamp > 0)
    2781             :     {
    2782             :         TimestampTz wakeup_time;
    2783             : 
    2784             :         /*
    2785             :          * At the latest stop sleeping once wal_sender_timeout has been
    2786             :          * reached.
    2787             :          */
    2788      126292 :         wakeup_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
    2789             :                                                   wal_sender_timeout);
    2790             : 
    2791             :         /*
    2792             :          * If no ping has been sent yet, wakeup when it's time to do so.
    2793             :          * WalSndKeepaliveIfNecessary() wants to send a keepalive once half of
    2794             :          * the timeout passed without a response.
    2795             :          */
    2796      126292 :         if (!waiting_for_ping_response)
    2797      115426 :             wakeup_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
    2798             :                                                       wal_sender_timeout / 2);
    2799             : 
    2800             :         /* Compute relative time until wakeup. */
    2801      126292 :         sleeptime = TimestampDifferenceMilliseconds(now, wakeup_time);
    2802             :     }
    2803             : 
    2804      126342 :     return sleeptime;
    2805             : }
    2806             : 
    2807             : /*
    2808             :  * Check whether there have been responses by the client within
    2809             :  * wal_sender_timeout and shutdown if not.  Using last_processing as the
    2810             :  * reference point avoids counting server-side stalls against the client.
    2811             :  * However, a long server-side stall can make WalSndKeepaliveIfNecessary()
    2812             :  * postdate last_processing by more than wal_sender_timeout.  If that happens,
    2813             :  * the client must reply almost immediately to avoid a timeout.  This rarely
    2814             :  * affects the default configuration, under which clients spontaneously send a
    2815             :  * message every standby_message_timeout = wal_sender_timeout/6 = 10s.  We
    2816             :  * could eliminate that problem by recognizing timeout expiration at
    2817             :  * wal_sender_timeout/2 after the keepalive.
    2818             :  */
    2819             : static void
    2820     1517656 : WalSndCheckTimeOut(void)
    2821             : {
    2822             :     TimestampTz timeout;
    2823             : 
    2824             :     /* don't bail out if we're doing something that doesn't require timeouts */
    2825     1517656 :     if (last_reply_timestamp <= 0)
    2826          50 :         return;
    2827             : 
    2828     1517606 :     timeout = TimestampTzPlusMilliseconds(last_reply_timestamp,
    2829             :                                           wal_sender_timeout);
    2830             : 
    2831     1517606 :     if (wal_sender_timeout > 0 && last_processing >= timeout)
    2832             :     {
    2833             :         /*
    2834             :          * Since typically expiration of replication timeout means
    2835             :          * communication problem, we don't send the error message to the
    2836             :          * standby.
    2837             :          */
    2838           0 :         ereport(COMMERROR,
    2839             :                 (errmsg("terminating walsender process due to replication timeout")));
    2840             : 
    2841           0 :         WalSndShutdown();
    2842             :     }
    2843             : }
    2844             : 
    2845             : /* Main loop of walsender process that streams the WAL over Copy messages. */
    2846             : static void
    2847        1322 : WalSndLoop(WalSndSendDataCallback send_data)
    2848             : {
    2849        1322 :     TimestampTz last_flush = 0;
    2850             : 
    2851             :     /*
    2852             :      * Initialize the last reply timestamp. That enables timeout processing
    2853             :      * from hereon.
    2854             :      */
    2855        1322 :     last_reply_timestamp = GetCurrentTimestamp();
    2856        1322 :     waiting_for_ping_response = false;
    2857             : 
    2858             :     /*
    2859             :      * Loop until we reach the end of this timeline or the client requests to
    2860             :      * stop streaming.
    2861             :      */
    2862             :     for (;;)
    2863             :     {
    2864             :         /* Clear any already-pending wakeups */
    2865     1509342 :         ResetLatch(MyLatch);
    2866             : 
    2867     1509342 :         CHECK_FOR_INTERRUPTS();
    2868             : 
    2869             :         /* Process any requests or signals received recently */
    2870     1509334 :         if (ConfigReloadPending)
    2871             :         {
    2872          34 :             ConfigReloadPending = false;
    2873          34 :             ProcessConfigFile(PGC_SIGHUP);
    2874          34 :             SyncRepInitConfig();
    2875             :         }
    2876             : 
    2877             :         /* Check for input from the client */
    2878     1509334 :         ProcessRepliesIfAny();
    2879             : 
    2880             :         /*
    2881             :          * If we have received CopyDone from the client, sent CopyDone
    2882             :          * ourselves, and the output buffer is empty, it's time to exit
    2883             :          * streaming.
    2884             :          */
    2885     1509170 :         if (streamingDoneReceiving && streamingDoneSending &&
    2886        1198 :             !pq_is_send_pending())
    2887         676 :             break;
    2888             : 
    2889             :         /*
    2890             :          * If we don't have any pending data in the output buffer, try to send
    2891             :          * some more.  If there is some, we don't bother to call send_data
    2892             :          * again until we've flushed it ... but we'd better assume we are not
    2893             :          * caught up.
    2894             :          */
    2895     1508494 :         if (!pq_is_send_pending())
    2896     1426112 :             send_data();
    2897             :         else
    2898       82382 :             WalSndCaughtUp = false;
    2899             : 
    2900             :         /* Try to flush pending output to the client */
    2901     1508092 :         if (pq_flush_if_writable() != 0)
    2902           0 :             WalSndShutdown();
    2903             : 
    2904             :         /* If nothing remains to be sent right now ... */
    2905     1508092 :         if (WalSndCaughtUp && !pq_is_send_pending())
    2906             :         {
    2907             :             /*
    2908             :              * If we're in catchup state, move to streaming.  This is an
    2909             :              * important state change for users to know about, since before
    2910             :              * this point data loss might occur if the primary dies and we
    2911             :              * need to failover to the standby. The state change is also
    2912             :              * important for synchronous replication, since commits that
    2913             :              * started to wait at that point might wait for some time.
    2914             :              */
    2915       96880 :             if (MyWalSnd->state == WALSNDSTATE_CATCHUP)
    2916             :             {
    2917        1024 :                 ereport(DEBUG1,
    2918             :                         (errmsg_internal("\"%s\" has now caught up with upstream server",
    2919             :                                          application_name)));
    2920        1024 :                 WalSndSetState(WALSNDSTATE_STREAMING);
    2921             :             }
    2922             : 
    2923             :             /*
    2924             :              * When SIGUSR2 arrives, we send any outstanding logs up to the
    2925             :              * shutdown checkpoint record (i.e., the latest record), wait for
    2926             :              * them to be replicated to the standby, and exit. This may be a
    2927             :              * normal termination at shutdown, or a promotion, the walsender
    2928             :              * is not sure which.
    2929             :              */
    2930       96880 :             if (got_SIGUSR2)
    2931       12356 :                 WalSndDone(send_data);
    2932             :         }
    2933             : 
    2934             :         /* Check for replication timeout. */
    2935     1508020 :         WalSndCheckTimeOut();
    2936             : 
    2937             :         /* Send keepalive if the time has come */
    2938     1508020 :         WalSndKeepaliveIfNecessary();
    2939             : 
    2940             :         /*
    2941             :          * Block if we have unsent data.  XXX For logical replication, let
    2942             :          * WalSndWaitForWal() handle any other blocking; idle receivers need
    2943             :          * its additional actions.  For physical replication, also block if
    2944             :          * caught up; its send_data does not block.
    2945             :          *
    2946             :          * The IO statistics are reported in WalSndWaitForWal() for the
    2947             :          * logical WAL senders.
    2948             :          */
    2949     1508020 :         if ((WalSndCaughtUp && send_data != XLogSendLogical &&
    2950     1556914 :              !streamingDoneSending) ||
    2951     1467182 :             pq_is_send_pending())
    2952             :         {
    2953             :             long        sleeptime;
    2954             :             int         wakeEvents;
    2955             :             TimestampTz now;
    2956             : 
    2957      117382 :             if (!streamingDoneReceiving)
    2958      117364 :                 wakeEvents = WL_SOCKET_READABLE;
    2959             :             else
    2960          18 :                 wakeEvents = 0;
    2961             : 
    2962             :             /*
    2963             :              * Use fresh timestamp, not last_processing, to reduce the chance
    2964             :              * of reaching wal_sender_timeout before sending a keepalive.
    2965             :              */
    2966      117382 :             now = GetCurrentTimestamp();
    2967      117382 :             sleeptime = WalSndComputeSleeptime(now);
    2968             : 
    2969      117382 :             if (pq_is_send_pending())
    2970       82052 :                 wakeEvents |= WL_SOCKET_WRITEABLE;
    2971             : 
    2972             :             /* Report IO statistics, if needed */
    2973      117382 :             if (TimestampDifferenceExceeds(last_flush, now,
    2974             :                                            WALSENDER_STATS_FLUSH_INTERVAL))
    2975             :             {
    2976        1246 :                 pgstat_flush_io(false);
    2977        1246 :                 (void) pgstat_flush_backend(false, PGSTAT_BACKEND_FLUSH_IO);
    2978        1246 :                 last_flush = now;
    2979             :             }
    2980             : 
    2981             :             /* Sleep until something happens or we time out */
    2982      117382 :             WalSndWait(wakeEvents, sleeptime, WAIT_EVENT_WAL_SENDER_MAIN);
    2983             :         }
    2984             :     }
    2985         676 : }
    2986             : 
    2987             : /* Initialize a per-walsender data structure for this walsender process */
    2988             : static void
    2989        2282 : InitWalSenderSlot(void)
    2990             : {
    2991             :     int         i;
    2992             : 
    2993             :     /*
    2994             :      * WalSndCtl should be set up already (we inherit this by fork() or
    2995             :      * EXEC_BACKEND mechanism from the postmaster).
    2996             :      */
    2997             :     Assert(WalSndCtl != NULL);
    2998             :     Assert(MyWalSnd == NULL);
    2999             : 
    3000             :     /*
    3001             :      * Find a free walsender slot and reserve it. This must not fail due to
    3002             :      * the prior check for free WAL senders in InitProcess().
    3003             :      */
    3004        3338 :     for (i = 0; i < max_wal_senders; i++)
    3005             :     {
    3006        3338 :         WalSnd     *walsnd = &WalSndCtl->walsnds[i];
    3007             : 
    3008        3338 :         SpinLockAcquire(&walsnd->mutex);
    3009             : 
    3010        3338 :         if (walsnd->pid != 0)
    3011             :         {
    3012        1056 :             SpinLockRelease(&walsnd->mutex);
    3013        1056 :             continue;
    3014             :         }
    3015             :         else
    3016             :         {
    3017             :             /*
    3018             :              * Found a free slot. Reserve it for us.
    3019             :              */
    3020        2282 :             walsnd->pid = MyProcPid;
    3021        2282 :             walsnd->state = WALSNDSTATE_STARTUP;
    3022        2282 :             walsnd->sentPtr = InvalidXLogRecPtr;
    3023        2282 :             walsnd->needreload = false;
    3024        2282 :             walsnd->write = InvalidXLogRecPtr;
    3025        2282 :             walsnd->flush = InvalidXLogRecPtr;
    3026        2282 :             walsnd->apply = InvalidXLogRecPtr;
    3027        2282 :             walsnd->writeLag = -1;
    3028        2282 :             walsnd->flushLag = -1;
    3029        2282 :             walsnd->applyLag = -1;
    3030        2282 :             walsnd->sync_standby_priority = 0;
    3031        2282 :             walsnd->replyTime = 0;
    3032             : 
    3033             :             /*
    3034             :              * The kind assignment is done here and not in StartReplication()
    3035             :              * and StartLogicalReplication(). Indeed, the logical walsender
    3036             :              * needs to read WAL records (like snapshot of running
    3037             :              * transactions) during the slot creation. So it needs to be woken
    3038             :              * up based on its kind.
    3039             :              *
    3040             :              * The kind assignment could also be done in StartReplication(),
    3041             :              * StartLogicalReplication() and CREATE_REPLICATION_SLOT but it
    3042             :              * seems better to set it on one place.
    3043             :              */
    3044        2282 :             if (MyDatabaseId == InvalidOid)
    3045         906 :                 walsnd->kind = REPLICATION_KIND_PHYSICAL;
    3046             :             else
    3047        1376 :                 walsnd->kind = REPLICATION_KIND_LOGICAL;
    3048             : 
    3049        2282 :             SpinLockRelease(&walsnd->mutex);
    3050             :             /* don't need the lock anymore */
    3051        2282 :             MyWalSnd = (WalSnd *) walsnd;
    3052             : 
    3053        2282 :             break;
    3054             :         }
    3055             :     }
    3056             : 
    3057             :     Assert(MyWalSnd != NULL);
    3058             : 
    3059             :     /* Arrange to clean up at walsender exit */
    3060        2282 :     on_shmem_exit(WalSndKill, 0);
    3061        2282 : }
    3062             : 
    3063             : /* Destroy the per-walsender data structure for this walsender process */
    3064             : static void
    3065        2282 : WalSndKill(int code, Datum arg)
    3066             : {
    3067        2282 :     WalSnd     *walsnd = MyWalSnd;
    3068             : 
    3069             :     Assert(walsnd != NULL);
    3070             : 
    3071        2282 :     MyWalSnd = NULL;
    3072             : 
    3073        2282 :     SpinLockAcquire(&walsnd->mutex);
    3074             :     /* Mark WalSnd struct as no longer being in use. */
    3075        2282 :     walsnd->pid = 0;
    3076        2282 :     SpinLockRelease(&walsnd->mutex);
    3077        2282 : }
    3078             : 
    3079             : /* XLogReaderRoutine->segment_open callback */
    3080             : static void
    3081       10122 : WalSndSegmentOpen(XLogReaderState *state, XLogSegNo nextSegNo,
    3082             :                   TimeLineID *tli_p)
    3083             : {
    3084             :     char        path[MAXPGPATH];
    3085             : 
    3086             :     /*-------
    3087             :      * When reading from a historic timeline, and there is a timeline switch
    3088             :      * within this segment, read from the WAL segment belonging to the new
    3089             :      * timeline.
    3090             :      *
    3091             :      * For example, imagine that this server is currently on timeline 5, and
    3092             :      * we're streaming timeline 4. The switch from timeline 4 to 5 happened at
    3093             :      * 0/13002088. In pg_wal, we have these files:
    3094             :      *
    3095             :      * ...
    3096             :      * 000000040000000000000012
    3097             :      * 000000040000000000000013
    3098             :      * 000000050000000000000013
    3099             :      * 000000050000000000000014
    3100             :      * ...
    3101             :      *
    3102             :      * In this situation, when requested to send the WAL from segment 0x13, on
    3103             :      * timeline 4, we read the WAL from file 000000050000000000000013. Archive
    3104             :      * recovery prefers files from newer timelines, so if the segment was
    3105             :      * restored from the archive on this server, the file belonging to the old
    3106             :      * timeline, 000000040000000000000013, might not exist. Their contents are
    3107             :      * equal up to the switchpoint, because at a timeline switch, the used
    3108             :      * portion of the old segment is copied to the new file.
    3109             :      */
    3110       10122 :     *tli_p = sendTimeLine;
    3111       10122 :     if (sendTimeLineIsHistoric)
    3112             :     {
    3113             :         XLogSegNo   endSegNo;
    3114             : 
    3115          24 :         XLByteToSeg(sendTimeLineValidUpto, endSegNo, state->segcxt.ws_segsize);
    3116          24 :         if (nextSegNo == endSegNo)
    3117          20 :             *tli_p = sendTimeLineNextTLI;
    3118             :     }
    3119             : 
    3120       10122 :     XLogFilePath(path, *tli_p, nextSegNo, state->segcxt.ws_segsize);
    3121       10122 :     state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY);
    3122       10122 :     if (state->seg.ws_file >= 0)
    3123       10122 :         return;
    3124             : 
    3125             :     /*
    3126             :      * If the file is not found, assume it's because the standby asked for a
    3127             :      * too old WAL segment that has already been removed or recycled.
    3128             :      */
    3129           0 :     if (errno == ENOENT)
    3130             :     {
    3131             :         char        xlogfname[MAXFNAMELEN];
    3132           0 :         int         save_errno = errno;
    3133             : 
    3134           0 :         XLogFileName(xlogfname, *tli_p, nextSegNo, wal_segment_size);
    3135           0 :         errno = save_errno;
    3136           0 :         ereport(ERROR,
    3137             :                 (errcode_for_file_access(),
    3138             :                  errmsg("requested WAL segment %s has already been removed",
    3139             :                         xlogfname)));
    3140             :     }
    3141             :     else
    3142           0 :         ereport(ERROR,
    3143             :                 (errcode_for_file_access(),
    3144             :                  errmsg("could not open file \"%s\": %m",
    3145             :                         path)));
    3146             : }
    3147             : 
    3148             : /*
    3149             :  * Send out the WAL in its normal physical/stored form.
    3150             :  *
    3151             :  * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
    3152             :  * but not yet sent to the client, and buffer it in the libpq output
    3153             :  * buffer.
    3154             :  *
    3155             :  * If there is no unsent WAL remaining, WalSndCaughtUp is set to true,
    3156             :  * otherwise WalSndCaughtUp is set to false.
    3157             :  */
    3158             : static void
    3159      286480 : XLogSendPhysical(void)
    3160             : {
    3161             :     XLogRecPtr  SendRqstPtr;
    3162             :     XLogRecPtr  startptr;
    3163             :     XLogRecPtr  endptr;
    3164             :     Size        nbytes;
    3165             :     XLogSegNo   segno;
    3166             :     WALReadError errinfo;
    3167             :     Size        rbytes;
    3168             : 
    3169             :     /* If requested switch the WAL sender to the stopping state. */
    3170      286480 :     if (got_STOPPING)
    3171       18332 :         WalSndSetState(WALSNDSTATE_STOPPING);
    3172             : 
    3173      286480 :     if (streamingDoneSending)
    3174             :     {
    3175       48868 :         WalSndCaughtUp = true;
    3176       86708 :         return;
    3177             :     }
    3178             : 
    3179             :     /* Figure out how far we can safely send the WAL. */
    3180      237612 :     if (sendTimeLineIsHistoric)
    3181             :     {
    3182             :         /*
    3183             :          * Streaming an old timeline that's in this server's history, but is
    3184             :          * not the one we're currently inserting or replaying. It can be
    3185             :          * streamed up to the point where we switched off that timeline.
    3186             :          */
    3187         330 :         SendRqstPtr = sendTimeLineValidUpto;
    3188             :     }
    3189      237282 :     else if (am_cascading_walsender)
    3190             :     {
    3191             :         TimeLineID  SendRqstTLI;
    3192             : 
    3193             :         /*
    3194             :          * Streaming the latest timeline on a standby.
    3195             :          *
    3196             :          * Attempt to send all WAL that has already been replayed, so that we
    3197             :          * know it's valid. If we're receiving WAL through streaming
    3198             :          * replication, it's also OK to send any WAL that has been received
    3199             :          * but not replayed.
    3200             :          *
    3201             :          * The timeline we're recovering from can change, or we can be
    3202             :          * promoted. In either case, the current timeline becomes historic. We
    3203             :          * need to detect that so that we don't try to stream past the point
    3204             :          * where we switched to another timeline. We check for promotion or
    3205             :          * timeline switch after calculating FlushPtr, to avoid a race
    3206             :          * condition: if the timeline becomes historic just after we checked
    3207             :          * that it was still current, it's still be OK to stream it up to the
    3208             :          * FlushPtr that was calculated before it became historic.
    3209             :          */
    3210        1518 :         bool        becameHistoric = false;
    3211             : 
    3212        1518 :         SendRqstPtr = GetStandbyFlushRecPtr(&SendRqstTLI);
    3213             : 
    3214        1518 :         if (!RecoveryInProgress())
    3215             :         {
    3216             :             /* We have been promoted. */
    3217           2 :             SendRqstTLI = GetWALInsertionTimeLine();
    3218           2 :             am_cascading_walsender = false;
    3219           2 :             becameHistoric = true;
    3220             :         }
    3221             :         else
    3222             :         {
    3223             :             /*
    3224             :              * Still a cascading standby. But is the timeline we're sending
    3225             :              * still the one recovery is recovering from?
    3226             :              */
    3227        1516 :             if (sendTimeLine != SendRqstTLI)
    3228           0 :                 becameHistoric = true;
    3229             :         }
    3230             : 
    3231        1518 :         if (becameHistoric)
    3232             :         {
    3233             :             /*
    3234             :              * The timeline we were sending has become historic. Read the
    3235             :              * timeline history file of the new timeline to see where exactly
    3236             :              * we forked off from the timeline we were sending.
    3237             :              */
    3238             :             List       *history;
    3239             : 
    3240           2 :             history = readTimeLineHistory(SendRqstTLI);
    3241           2 :             sendTimeLineValidUpto = tliSwitchPoint(sendTimeLine, history, &sendTimeLineNextTLI);
    3242             : 
    3243             :             Assert(sendTimeLine < sendTimeLineNextTLI);
    3244           2 :             list_free_deep(history);
    3245             : 
    3246           2 :             sendTimeLineIsHistoric = true;
    3247             : 
    3248           2 :             SendRqstPtr = sendTimeLineValidUpto;
    3249             :         }
    3250             :     }
    3251             :     else
    3252             :     {
    3253             :         /*
    3254             :          * Streaming the current timeline on a primary.
    3255             :          *
    3256             :          * Attempt to send all data that's already been written out and
    3257             :          * fsync'd to disk.  We cannot go further than what's been written out
    3258             :          * given the current implementation of WALRead().  And in any case
    3259             :          * it's unsafe to send WAL that is not securely down to disk on the
    3260             :          * primary: if the primary subsequently crashes and restarts, standbys
    3261             :          * must not have applied any WAL that got lost on the primary.
    3262             :          */
    3263      235764 :         SendRqstPtr = GetFlushRecPtr(NULL);
    3264             :     }
    3265             : 
    3266             :     /*
    3267             :      * Record the current system time as an approximation of the time at which
    3268             :      * this WAL location was written for the purposes of lag tracking.
    3269             :      *
    3270             :      * In theory we could make XLogFlush() record a time in shmem whenever WAL
    3271             :      * is flushed and we could get that time as well as the LSN when we call
    3272             :      * GetFlushRecPtr() above (and likewise for the cascading standby
    3273             :      * equivalent), but rather than putting any new code into the hot WAL path
    3274             :      * it seems good enough to capture the time here.  We should reach this
    3275             :      * after XLogFlush() runs WalSndWakeupProcessRequests(), and although that
    3276             :      * may take some time, we read the WAL flush pointer and take the time
    3277             :      * very close to together here so that we'll get a later position if it is
    3278             :      * still moving.
    3279             :      *
    3280             :      * Because LagTrackerWrite ignores samples when the LSN hasn't advanced,
    3281             :      * this gives us a cheap approximation for the WAL flush time for this
    3282             :      * LSN.
    3283             :      *
    3284             :      * Note that the LSN is not necessarily the LSN for the data contained in
    3285             :      * the present message; it's the end of the WAL, which might be further
    3286             :      * ahead.  All the lag tracking machinery cares about is finding out when
    3287             :      * that arbitrary LSN is eventually reported as written, flushed and
    3288             :      * applied, so that it can measure the elapsed time.
    3289             :      */
    3290      237612 :     LagTrackerWrite(SendRqstPtr, GetCurrentTimestamp());
    3291             : 
    3292             :     /*
    3293             :      * If this is a historic timeline and we've reached the point where we
    3294             :      * forked to the next timeline, stop streaming.
    3295             :      *
    3296             :      * Note: We might already have sent WAL > sendTimeLineValidUpto. The
    3297             :      * startup process will normally replay all WAL that has been received
    3298             :      * from the primary, before promoting, but if the WAL streaming is
    3299             :      * terminated at a WAL page boundary, the valid portion of the timeline
    3300             :      * might end in the middle of a WAL record. We might've already sent the
    3301             :      * first half of that partial WAL record to the cascading standby, so that
    3302             :      * sentPtr > sendTimeLineValidUpto. That's OK; the cascading standby can't
    3303             :      * replay the partial WAL record either, so it can still follow our
    3304             :      * timeline switch.
    3305             :      */
    3306      237612 :     if (sendTimeLineIsHistoric && sendTimeLineValidUpto <= sentPtr)
    3307             :     {
    3308             :         /* close the current file. */
    3309          26 :         if (xlogreader->seg.ws_file >= 0)
    3310          26 :             wal_segment_close(xlogreader);
    3311             : 
    3312             :         /* Send CopyDone */
    3313          26 :         pq_putmessage_noblock(PqMsg_CopyDone, NULL, 0);
    3314          26 :         streamingDoneSending = true;
    3315             : 
    3316          26 :         WalSndCaughtUp = true;
    3317             : 
    3318          26 :         elog(DEBUG1, "walsender reached end of timeline at %X/%08X (sent up to %X/%08X)",
    3319             :              LSN_FORMAT_ARGS(sendTimeLineValidUpto),
    3320             :              LSN_FORMAT_ARGS(sentPtr));
    3321          26 :         return;
    3322             :     }
    3323             : 
    3324             :     /* Do we have any work to do? */
    3325             :     Assert(sentPtr <= SendRqstPtr);
    3326      237586 :     if (SendRqstPtr <= sentPtr)
    3327             :     {
    3328       37814 :         WalSndCaughtUp = true;
    3329       37814 :         return;
    3330             :     }
    3331             : 
    3332             :     /*
    3333             :      * Figure out how much to send in one message. If there's no more than
    3334             :      * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
    3335             :      * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
    3336             :      *
    3337             :      * The rounding is not only for performance reasons. Walreceiver relies on
    3338             :      * the fact that we never split a WAL record across two messages. Since a
    3339             :      * long WAL record is split at page boundary into continuation records,
    3340             :      * page boundary is always a safe cut-off point. We also assume that
    3341             :      * SendRqstPtr never points to the middle of a WAL record.
    3342             :      */
    3343      199772 :     startptr = sentPtr;
    3344      199772 :     endptr = startptr;
    3345      199772 :     endptr += MAX_SEND_SIZE;
    3346             : 
    3347             :     /* if we went beyond SendRqstPtr, back off */
    3348      199772 :     if (SendRqstPtr <= endptr)
    3349             :     {
    3350       11952 :         endptr = SendRqstPtr;
    3351       11952 :         if (sendTimeLineIsHistoric)
    3352          24 :             WalSndCaughtUp = false;
    3353             :         else
    3354       11928 :             WalSndCaughtUp = true;
    3355             :     }
    3356             :     else
    3357             :     {
    3358             :         /* round down to page boundary. */
    3359      187820 :         endptr -= (endptr % XLOG_BLCKSZ);
    3360      187820 :         WalSndCaughtUp = false;
    3361             :     }
    3362             : 
    3363      199772 :     nbytes = endptr - startptr;
    3364             :     Assert(nbytes <= MAX_SEND_SIZE);
    3365             : 
    3366             :     /*
    3367             :      * OK to read and send the slice.
    3368             :      */
    3369      199772 :     resetStringInfo(&output_message);
    3370      199772 :     pq_sendbyte(&output_message, PqReplMsg_WALData);
    3371             : 
    3372      199772 :     pq_sendint64(&output_message, startptr);    /* dataStart */
    3373      199772 :     pq_sendint64(&output_message, SendRqstPtr); /* walEnd */
    3374      199772 :     pq_sendint64(&output_message, 0);   /* sendtime, filled in last */
    3375             : 
    3376             :     /*
    3377             :      * Read the log directly into the output buffer to avoid extra memcpy
    3378             :      * calls.
    3379             :      */
    3380      199772 :     enlargeStringInfo(&output_message, nbytes);
    3381             : 
    3382      199772 : retry:
    3383             :     /* attempt to read WAL from WAL buffers first */
    3384      199772 :     rbytes = WALReadFromBuffers(&output_message.data[output_message.len],
    3385      199772 :                                 startptr, nbytes, xlogreader->seg.ws_tli);
    3386      199772 :     output_message.len += rbytes;
    3387      199772 :     startptr += rbytes;
    3388      199772 :     nbytes -= rbytes;
    3389             : 
    3390             :     /* now read the remaining WAL from WAL file */
    3391      199772 :     if (nbytes > 0 &&
    3392      193468 :         !WALRead(xlogreader,
    3393      193468 :                  &output_message.data[output_message.len],
    3394             :                  startptr,
    3395             :                  nbytes,
    3396      193468 :                  xlogreader->seg.ws_tli, /* Pass the current TLI because
    3397             :                                              * only WalSndSegmentOpen controls
    3398             :                                              * whether new TLI is needed. */
    3399             :                  &errinfo))
    3400           0 :         WALReadRaiseError(&errinfo);
    3401             : 
    3402             :     /* See logical_read_xlog_page(). */
    3403      199772 :     XLByteToSeg(startptr, segno, xlogreader->segcxt.ws_segsize);
    3404      199772 :     CheckXLogRemoved(segno, xlogreader->seg.ws_tli);
    3405             : 
    3406             :     /*
    3407             :      * During recovery, the currently-open WAL file might be replaced with the
    3408             :      * file of the same name retrieved from archive. So we always need to
    3409             :      * check what we read was valid after reading into the buffer. If it's
    3410             :      * invalid, we try to open and read the file again.
    3411             :      */
    3412      199772 :     if (am_cascading_walsender)
    3413             :     {
    3414        1112 :         WalSnd     *walsnd = MyWalSnd;
    3415             :         bool        reload;
    3416             : 
    3417        1112 :         SpinLockAcquire(&walsnd->mutex);
    3418        1112 :         reload = walsnd->needreload;
    3419        1112 :         walsnd->needreload = false;
    3420        1112 :         SpinLockRelease(&walsnd->mutex);
    3421             : 
    3422        1112 :         if (reload && xlogreader->seg.ws_file >= 0)
    3423             :         {
    3424           0 :             wal_segment_close(xlogreader);
    3425             : 
    3426           0 :             goto retry;
    3427             :         }
    3428             :     }
    3429             : 
    3430      199772 :     output_message.len += nbytes;
    3431      199772 :     output_message.data[output_message.len] = '\0';
    3432             : 
    3433             :     /*
    3434             :      * Fill the send timestamp last, so that it is taken as late as possible.
    3435             :      */
    3436      199772 :     resetStringInfo(&tmpbuf);
    3437      199772 :     pq_sendint64(&tmpbuf, GetCurrentTimestamp());
    3438      199772 :     memcpy(&output_message.data[1 + sizeof(int64) + sizeof(int64)],
    3439      199772 :            tmpbuf.data, sizeof(int64));
    3440             : 
    3441      199772 :     pq_putmessage_noblock(PqMsg_CopyData, output_message.data, output_message.len);
    3442             : 
    3443      199772 :     sentPtr = endptr;
    3444             : 
    3445             :     /* Update shared memory status */
    3446             :     {
    3447      199772 :         WalSnd     *walsnd = MyWalSnd;
    3448             : 
    3449      199772 :         SpinLockAcquire(&walsnd->mutex);
    3450      199772 :         walsnd->sentPtr = sentPtr;
    3451      199772 :         SpinLockRelease(&walsnd->mutex);
    3452             :     }
    3453             : 
    3454             :     /* Report progress of XLOG streaming in PS display */
    3455      199772 :     if (update_process_title)
    3456             :     {
    3457             :         char        activitymsg[50];
    3458             : 
    3459      199772 :         snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%08X",
    3460      199772 :                  LSN_FORMAT_ARGS(sentPtr));
    3461      199772 :         set_ps_display(activitymsg);
    3462             :     }
    3463             : }
    3464             : 
    3465             : /*
    3466             :  * Stream out logically decoded data.
    3467             :  */
    3468             : static void
    3469     1151988 : XLogSendLogical(void)
    3470             : {
    3471             :     XLogRecord *record;
    3472             :     char       *errm;
    3473             : 
    3474             :     /*
    3475             :      * We'll use the current flush point to determine whether we've caught up.
    3476             :      * This variable is static in order to cache it across calls.  Caching is
    3477             :      * helpful because GetFlushRecPtr() needs to acquire a heavily-contended
    3478             :      * spinlock.
    3479             :      */
    3480             :     static XLogRecPtr flushPtr = InvalidXLogRecPtr;
    3481             : 
    3482             :     /*
    3483             :      * Don't know whether we've caught up yet. We'll set WalSndCaughtUp to
    3484             :      * true in WalSndWaitForWal, if we're actually waiting. We also set to
    3485             :      * true if XLogReadRecord() had to stop reading but WalSndWaitForWal
    3486             :      * didn't wait - i.e. when we're shutting down.
    3487             :      */
    3488     1151988 :     WalSndCaughtUp = false;
    3489             : 
    3490     1151988 :     record = XLogReadRecord(logical_decoding_ctx->reader, &errm);
    3491             : 
    3492             :     /* xlog record was invalid */
    3493     1151646 :     if (errm != NULL)
    3494           0 :         elog(ERROR, "could not find record while sending logically-decoded data: %s",
    3495             :              errm);
    3496             : 
    3497     1151646 :     if (record != NULL)
    3498             :     {
    3499             :         /*
    3500             :          * Note the lack of any call to LagTrackerWrite() which is handled by
    3501             :          * WalSndUpdateProgress which is called by output plugin through
    3502             :          * logical decoding write api.
    3503             :          */
    3504     1144492 :         LogicalDecodingProcessRecord(logical_decoding_ctx, logical_decoding_ctx->reader);
    3505             : 
    3506     1144432 :         sentPtr = logical_decoding_ctx->reader->EndRecPtr;
    3507             :     }
    3508             : 
    3509             :     /*
    3510             :      * If first time through in this session, initialize flushPtr.  Otherwise,
    3511             :      * we only need to update flushPtr if EndRecPtr is past it.
    3512             :      */
    3513     1151586 :     if (flushPtr == InvalidXLogRecPtr ||
    3514     1151006 :         logical_decoding_ctx->reader->EndRecPtr >= flushPtr)
    3515             :     {
    3516             :         /*
    3517             :          * For cascading logical WAL senders, we use the replay LSN instead of
    3518             :          * the flush LSN, since logical decoding on a standby only processes
    3519             :          * WAL that has been replayed.  This distinction becomes particularly
    3520             :          * important during shutdown, as new WAL is no longer replayed and the
    3521             :          * last replayed LSN marks the furthest point up to which decoding can
    3522             :          * proceed.
    3523             :          */
    3524       12128 :         if (am_cascading_walsender)
    3525        1534 :             flushPtr = GetXLogReplayRecPtr(NULL);
    3526             :         else
    3527       10594 :             flushPtr = GetFlushRecPtr(NULL);
    3528             :     }
    3529             : 
    3530             :     /* If EndRecPtr is still past our flushPtr, it means we caught up. */
    3531     1151586 :     if (logical_decoding_ctx->reader->EndRecPtr >= flushPtr)
    3532        9924 :         WalSndCaughtUp = true;
    3533             : 
    3534             :     /*
    3535             :      * If we're caught up and have been requested to stop, have WalSndLoop()
    3536             :      * terminate the connection in an orderly manner, after writing out all
    3537             :      * the pending data.
    3538             :      */
    3539     1151586 :     if (WalSndCaughtUp && got_STOPPING)
    3540        7008 :         got_SIGUSR2 = true;
    3541             : 
    3542             :     /* Update shared memory status */
    3543             :     {
    3544     1151586 :         WalSnd     *walsnd = MyWalSnd;
    3545             : 
    3546     1151586 :         SpinLockAcquire(&walsnd->mutex);
    3547     1151586 :         walsnd->sentPtr = sentPtr;
    3548     1151586 :         SpinLockRelease(&walsnd->mutex);
    3549             :     }
    3550     1151586 : }
    3551             : 
    3552             : /*
    3553             :  * Shutdown if the sender is caught up.
    3554             :  *
    3555             :  * NB: This should only be called when the shutdown signal has been received
    3556             :  * from postmaster.
    3557             :  *
    3558             :  * Note that if we determine that there's still more data to send, this
    3559             :  * function will return control to the caller.
    3560             :  */
    3561             : static void
    3562       12356 : WalSndDone(WalSndSendDataCallback send_data)
    3563             : {
    3564             :     XLogRecPtr  replicatedPtr;
    3565             : 
    3566             :     /* ... let's just be real sure we're caught up ... */
    3567       12356 :     send_data();
    3568             : 
    3569             :     /*
    3570             :      * To figure out whether all WAL has successfully been replicated, check
    3571             :      * flush location if valid, write otherwise. Tools like pg_receivewal will
    3572             :      * usually (unless in synchronous mode) return an invalid flush location.
    3573             :      */
    3574       24712 :     replicatedPtr = XLogRecPtrIsInvalid(MyWalSnd->flush) ?
    3575       12356 :         MyWalSnd->write : MyWalSnd->flush;
    3576             : 
    3577       12356 :     if (WalSndCaughtUp && sentPtr == replicatedPtr &&
    3578          72 :         !pq_is_send_pending())
    3579             :     {
    3580             :         QueryCompletion qc;
    3581             : 
    3582             :         /* Inform the standby that XLOG streaming is done */
    3583          72 :         SetQueryCompletion(&qc, CMDTAG_COPY, 0);
    3584          72 :         EndCommand(&qc, DestRemote, false);
    3585          72 :         pq_flush();
    3586             : 
    3587          72 :         proc_exit(0);
    3588             :     }
    3589       12284 :     if (!waiting_for_ping_response)
    3590        6468 :         WalSndKeepalive(true, InvalidXLogRecPtr);
    3591       12284 : }
    3592             : 
    3593             : /*
    3594             :  * Returns the latest point in WAL that has been safely flushed to disk.
    3595             :  * This should only be called when in recovery.
    3596             :  *
    3597             :  * This is called either by cascading walsender to find WAL position to be sent
    3598             :  * to a cascaded standby or by slot synchronization operation to validate remote
    3599             :  * slot's lsn before syncing it locally.
    3600             :  *
    3601             :  * As a side-effect, *tli is updated to the TLI of the last
    3602             :  * replayed WAL record.
    3603             :  */
    3604             : XLogRecPtr
    3605        1734 : GetStandbyFlushRecPtr(TimeLineID *tli)
    3606             : {
    3607             :     XLogRecPtr  replayPtr;
    3608             :     TimeLineID  replayTLI;
    3609             :     XLogRecPtr  receivePtr;
    3610             :     TimeLineID  receiveTLI;
    3611             :     XLogRecPtr  result;
    3612             : 
    3613             :     Assert(am_cascading_walsender || IsSyncingReplicationSlots());
    3614             : 
    3615             :     /*
    3616             :      * We can safely send what's already been replayed. Also, if walreceiver
    3617             :      * is streaming WAL from the same timeline, we can send anything that it
    3618             :      * has streamed, but hasn't been replayed yet.
    3619             :      */
    3620             : 
    3621        1734 :     receivePtr = GetWalRcvFlushRecPtr(NULL, &receiveTLI);
    3622        1734 :     replayPtr = GetXLogReplayRecPtr(&replayTLI);
    3623             : 
    3624        1734 :     if (tli)
    3625        1660 :         *tli = replayTLI;
    3626             : 
    3627        1734 :     result = replayPtr;
    3628        1734 :     if (receiveTLI == replayTLI && receivePtr > replayPtr)
    3629          62 :         result = receivePtr;
    3630             : 
    3631        1734 :     return result;
    3632             : }
    3633             : 
    3634             : /*
    3635             :  * Request walsenders to reload the currently-open WAL file
    3636             :  */
    3637             : void
    3638          58 : WalSndRqstFileReload(void)
    3639             : {
    3640             :     int         i;
    3641             : 
    3642         590 :     for (i = 0; i < max_wal_senders; i++)
    3643             :     {
    3644         532 :         WalSnd     *walsnd = &WalSndCtl->walsnds[i];
    3645             : 
    3646         532 :         SpinLockAcquire(&walsnd->mutex);
    3647         532 :         if (walsnd->pid == 0)
    3648             :         {
    3649         532 :             SpinLockRelease(&walsnd->mutex);
    3650         532 :             continue;
    3651             :         }
    3652           0 :         walsnd->needreload = true;
    3653           0 :         SpinLockRelease(&walsnd->mutex);
    3654             :     }
    3655          58 : }
    3656             : 
    3657             : /*
    3658             :  * Handle PROCSIG_WALSND_INIT_STOPPING signal.
    3659             :  */
    3660             : void
    3661          72 : HandleWalSndInitStopping(void)
    3662             : {
    3663             :     Assert(am_walsender);
    3664             : 
    3665             :     /*
    3666             :      * If replication has not yet started, die like with SIGTERM. If
    3667             :      * replication is active, only set a flag and wake up the main loop. It
    3668             :      * will send any outstanding WAL, wait for it to be replicated to the
    3669             :      * standby, and then exit gracefully.
    3670             :      */
    3671          72 :     if (!replication_active)
    3672           0 :         kill(MyProcPid, SIGTERM);
    3673             :     else
    3674          72 :         got_STOPPING = true;
    3675          72 : }
    3676             : 
    3677             : /*
    3678             :  * SIGUSR2: set flag to do a last cycle and shut down afterwards. The WAL
    3679             :  * sender should already have been switched to WALSNDSTATE_STOPPING at
    3680             :  * this point.
    3681             :  */
    3682             : static void
    3683          66 : WalSndLastCycleHandler(SIGNAL_ARGS)
    3684             : {
    3685          66 :     got_SIGUSR2 = true;
    3686          66 :     SetLatch(MyLatch);
    3687          66 : }
    3688             : 
    3689             : /* Set up signal handlers */
    3690             : void
    3691        2282 : WalSndSignals(void)
    3692             : {
    3693             :     /* Set up signal handlers */
    3694        2282 :     pqsignal(SIGHUP, SignalHandlerForConfigReload);
    3695        2282 :     pqsignal(SIGINT, StatementCancelHandler);   /* query cancel */
    3696        2282 :     pqsignal(SIGTERM, die);     /* request shutdown */
    3697             :     /* SIGQUIT handler was already set up by InitPostmasterChild */
    3698        2282 :     InitializeTimeouts();       /* establishes SIGALRM handler */
    3699        2282 :     pqsignal(SIGPIPE, SIG_IGN);
    3700        2282 :     pqsignal(SIGUSR1, procsignal_sigusr1_handler);
    3701        2282 :     pqsignal(SIGUSR2, WalSndLastCycleHandler);  /* request a last cycle and
    3702             :                                                  * shutdown */
    3703             : 
    3704             :     /* Reset some signals that are accepted by postmaster but not here */
    3705        2282 :     pqsignal(SIGCHLD, SIG_DFL);
    3706        2282 : }
    3707             : 
    3708             : /* Report shared-memory space needed by WalSndShmemInit */
    3709             : Size
    3710        8308 : WalSndShmemSize(void)
    3711             : {
    3712        8308 :     Size        size = 0;
    3713             : 
    3714        8308 :     size = offsetof(WalSndCtlData, walsnds);
    3715        8308 :     size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
    3716             : 
    3717        8308 :     return size;
    3718             : }
    3719             : 
    3720             : /* Allocate and initialize walsender-related shared memory */
    3721             : void
    3722        2152 : WalSndShmemInit(void)
    3723             : {
    3724             :     bool        found;
    3725             :     int         i;
    3726             : 
    3727        2152 :     WalSndCtl = (WalSndCtlData *)
    3728        2152 :         ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
    3729             : 
    3730        2152 :     if (!found)
    3731             :     {
    3732             :         /* First time through, so initialize */
    3733       15272 :         MemSet(WalSndCtl, 0, WalSndShmemSize());
    3734             : 
    3735        8608 :         for (i = 0; i < NUM_SYNC_REP_WAIT_MODE; i++)
    3736        6456 :             dlist_init(&(WalSndCtl->SyncRepQueue[i]));
    3737             : 
    3738       16368 :         for (i = 0; i < max_wal_senders; i++)
    3739             :         {
    3740       14216 :             WalSnd     *walsnd = &WalSndCtl->walsnds[i];
    3741             : 
    3742       14216 :             SpinLockInit(&walsnd->mutex);
    3743             :         }
    3744             : 
    3745        2152 :         ConditionVariableInit(&WalSndCtl->wal_flush_cv);
    3746        2152 :         ConditionVariableInit(&WalSndCtl->wal_replay_cv);
    3747        2152 :         ConditionVariableInit(&WalSndCtl->wal_confirm_rcv_cv);
    3748             :     }
    3749        2152 : }
    3750             : 
    3751             : /*
    3752             :  * Wake up physical, logical or both kinds of walsenders
    3753             :  *
    3754             :  * The distinction between physical and logical walsenders is done, because:
    3755             :  * - physical walsenders can't send data until it's been flushed
    3756             :  * - logical walsenders on standby can't decode and send data until it's been
    3757             :  *   applied
    3758             :  *
    3759             :  * For cascading replication we need to wake up physical walsenders separately
    3760             :  * from logical walsenders (see the comment before calling WalSndWakeup() in
    3761             :  * ApplyWalRecord() for more details).
    3762             :  *
    3763             :  * This will be called inside critical sections, so throwing an error is not
    3764             :  * advisable.
    3765             :  */
    3766             : void
    3767     5381358 : WalSndWakeup(bool physical, bool logical)
    3768             : {
    3769             :     /*
    3770             :      * Wake up all the walsenders waiting on WAL being flushed or replayed
    3771             :      * respectively.  Note that waiting walsender would have prepared to sleep
    3772             :      * on the CV (i.e., added itself to the CV's waitlist) in WalSndWait()
    3773             :      * before actually waiting.
    3774             :      */
    3775     5381358 :     if (physical)
    3776      268738 :         ConditionVariableBroadcast(&WalSndCtl->wal_flush_cv);
    3777             : 
    3778     5381358 :     if (logical)
    3779     5318136 :         ConditionVariableBroadcast(&WalSndCtl->wal_replay_cv);
    3780     5381358 : }
    3781             : 
    3782             : /*
    3783             :  * Wait for readiness on the FeBe socket, or a timeout.  The mask should be
    3784             :  * composed of optional WL_SOCKET_WRITEABLE and WL_SOCKET_READABLE flags.  Exit
    3785             :  * on postmaster death.
    3786             :  */
    3787             : static void
    3788      126342 : WalSndWait(uint32 socket_events, long timeout, uint32 wait_event)
    3789             : {
    3790             :     WaitEvent   event;
    3791             : 
    3792      126342 :     ModifyWaitEvent(FeBeWaitSet, FeBeWaitSetSocketPos, socket_events, NULL);
    3793             : 
    3794             :     /*
    3795             :      * We use a condition variable to efficiently wake up walsenders in
    3796             :      * WalSndWakeup().
    3797             :      *
    3798             :      * Every walsender prepares to sleep on a shared memory CV. Note that it
    3799             :      * just prepares to sleep on the CV (i.e., adds itself to the CV's
    3800             :      * waitlist), but does not actually wait on the CV (IOW, it never calls
    3801             :      * ConditionVariableSleep()). It still uses WaitEventSetWait() for
    3802             :      * waiting, because we also need to wait for socket events. The processes
    3803             :      * (startup process, walreceiver etc.) wanting to wake up walsenders use
    3804             :      * ConditionVariableBroadcast(), which in turn calls SetLatch(), helping
    3805             :      * walsenders come out of WaitEventSetWait().
    3806             :      *
    3807             :      * This approach is simple and efficient because, one doesn't have to loop
    3808             :      * through all the walsenders slots, with a spinlock acquisition and
    3809             :      * release for every iteration, just to wake up only the waiting
    3810             :      * walsenders. It makes WalSndWakeup() callers' life easy.
    3811             :      *
    3812             :      * XXX: A desirable future improvement would be to add support for CVs
    3813             :      * into WaitEventSetWait().
    3814             :      *
    3815             :      * And, we use separate shared memory CVs for physical and logical
    3816             :      * walsenders for selective wake ups, see WalSndWakeup() for more details.
    3817             :      *
    3818             :      * If the wait event is WAIT_FOR_STANDBY_CONFIRMATION, wait on another CV
    3819             :      * until awakened by physical walsenders after the walreceiver confirms
    3820             :      * the receipt of the LSN.
    3821             :      */
    3822      126342 :     if (wait_event == WAIT_EVENT_WAIT_FOR_STANDBY_CONFIRMATION)
    3823          10 :         ConditionVariablePrepareToSleep(&WalSndCtl->wal_confirm_rcv_cv);
    3824      126332 :     else if (MyWalSnd->kind == REPLICATION_KIND_PHYSICAL)
    3825      115316 :         ConditionVariablePrepareToSleep(&WalSndCtl->wal_flush_cv);
    3826       11016 :     else if (MyWalSnd->kind == REPLICATION_KIND_LOGICAL)
    3827       11016 :         ConditionVariablePrepareToSleep(&WalSndCtl->wal_replay_cv);
    3828             : 
    3829      126342 :     if (WaitEventSetWait(FeBeWaitSet, timeout, &event, 1, wait_event) == 1 &&
    3830      126342 :         (event.events & WL_POSTMASTER_DEATH))
    3831             :     {
    3832           0 :         ConditionVariableCancelSleep();
    3833           0 :         proc_exit(1);
    3834             :     }
    3835             : 
    3836      126342 :     ConditionVariableCancelSleep();
    3837      126342 : }
    3838             : 
    3839             : /*
    3840             :  * Signal all walsenders to move to stopping state.
    3841             :  *
    3842             :  * This will trigger walsenders to move to a state where no further WAL can be
    3843             :  * generated. See this file's header for details.
    3844             :  */
    3845             : void
    3846        1272 : WalSndInitStopping(void)
    3847             : {
    3848             :     int         i;
    3849             : 
    3850        9876 :     for (i = 0; i < max_wal_senders; i++)
    3851             :     {
    3852        8604 :         WalSnd     *walsnd = &WalSndCtl->walsnds[i];
    3853             :         pid_t       pid;
    3854             : 
    3855        8604 :         SpinLockAcquire(&walsnd->mutex);
    3856        8604 :         pid = walsnd->pid;
    3857        8604 :         SpinLockRelease(&walsnd->mutex);
    3858             : 
    3859        8604 :         if (pid == 0)
    3860        8532 :             continue;
    3861             : 
    3862          72 :         SendProcSignal(pid, PROCSIG_WALSND_INIT_STOPPING, INVALID_PROC_NUMBER);
    3863             :     }
    3864        1272 : }
    3865             : 
    3866             : /*
    3867             :  * Wait that all the WAL senders have quit or reached the stopping state. This
    3868             :  * is used by the checkpointer to control when the shutdown checkpoint can
    3869             :  * safely be performed.
    3870             :  */
    3871             : void
    3872        1272 : WalSndWaitStopping(void)
    3873             : {
    3874             :     for (;;)
    3875          70 :     {
    3876             :         int         i;
    3877        1342 :         bool        all_stopped = true;
    3878             : 
    3879        9952 :         for (i = 0; i < max_wal_senders; i++)
    3880             :         {
    3881        8680 :             WalSnd     *walsnd = &WalSndCtl->walsnds[i];
    3882             : 
    3883        8680 :             SpinLockAcquire(&walsnd->mutex);
    3884             : 
    3885        8680 :             if (walsnd->pid == 0)
    3886             :             {
    3887        8558 :                 SpinLockRelease(&walsnd->mutex);
    3888        8558 :                 continue;
    3889             :             }
    3890             : 
    3891         122 :             if (walsnd->state != WALSNDSTATE_STOPPING)
    3892             :             {
    3893          70 :                 all_stopped = false;
    3894          70 :                 SpinLockRelease(&walsnd->mutex);
    3895          70 :                 break;
    3896             :             }
    3897          52 :             SpinLockRelease(&walsnd->mutex);
    3898             :         }
    3899             : 
    3900             :         /* safe to leave if confirmation is done for all WAL senders */
    3901        1342 :         if (all_stopped)
    3902        1272 :             return;
    3903             : 
    3904          70 :         pg_usleep(10000L);      /* wait for 10 msec */
    3905             :     }
    3906             : }
    3907             : 
    3908             : /* Set state for current walsender (only called in walsender) */
    3909             : void
    3910       21776 : WalSndSetState(WalSndState state)
    3911             : {
    3912       21776 :     WalSnd     *walsnd = MyWalSnd;
    3913             : 
    3914             :     Assert(am_walsender);
    3915             : 
    3916       21776 :     if (walsnd->state == state)
    3917       18350 :         return;
    3918             : 
    3919        3426 :     SpinLockAcquire(&walsnd->mutex);
    3920        3426 :     walsnd->state = state;
    3921        3426 :     SpinLockRelease(&walsnd->mutex);
    3922             : }
    3923             : 
    3924             : /*
    3925             :  * Return a string constant representing the state. This is used
    3926             :  * in system views, and should *not* be translated.
    3927             :  */
    3928             : static const char *
    3929        1982 : WalSndGetStateString(WalSndState state)
    3930             : {
    3931        1982 :     switch (state)
    3932             :     {
    3933           8 :         case WALSNDSTATE_STARTUP:
    3934           8 :             return "startup";
    3935           0 :         case WALSNDSTATE_BACKUP:
    3936           0 :             return "backup";
    3937          22 :         case WALSNDSTATE_CATCHUP:
    3938          22 :             return "catchup";
    3939        1952 :         case WALSNDSTATE_STREAMING:
    3940        1952 :             return "streaming";
    3941           0 :         case WALSNDSTATE_STOPPING:
    3942           0 :             return "stopping";
    3943             :     }
    3944           0 :     return "UNKNOWN";
    3945             : }
    3946             : 
    3947             : static Interval *
    3948        3374 : offset_to_interval(TimeOffset offset)
    3949             : {
    3950        3374 :     Interval   *result = palloc(sizeof(Interval));
    3951             : 
    3952        3374 :     result->month = 0;
    3953        3374 :     result->day = 0;
    3954        3374 :     result->time = offset;
    3955             : 
    3956        3374 :     return result;
    3957             : }
    3958             : 
    3959             : /*
    3960             :  * Returns activity of walsenders, including pids and xlog locations sent to
    3961             :  * standby servers.
    3962             :  */
    3963             : Datum
    3964        1696 : pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
    3965             : {
    3966             : #define PG_STAT_GET_WAL_SENDERS_COLS    12
    3967        1696 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    3968             :     SyncRepStandbyData *sync_standbys;
    3969             :     int         num_standbys;
    3970             :     int         i;
    3971             : 
    3972        1696 :     InitMaterializedSRF(fcinfo, 0);
    3973             : 
    3974             :     /*
    3975             :      * Get the currently active synchronous standbys.  This could be out of
    3976             :      * date before we're done, but we'll use the data anyway.
    3977             :      */
    3978        1696 :     num_standbys = SyncRepGetCandidateStandbys(&sync_standbys);
    3979             : 
    3980       18148 :     for (i = 0; i < max_wal_senders; i++)
    3981             :     {
    3982       16452 :         WalSnd     *walsnd = &WalSndCtl->walsnds[i];
    3983             :         XLogRecPtr  sent_ptr;
    3984             :         XLogRecPtr  write;
    3985             :         XLogRecPtr  flush;
    3986             :         XLogRecPtr  apply;
    3987             :         TimeOffset  writeLag;
    3988             :         TimeOffset  flushLag;
    3989             :         TimeOffset  applyLag;
    3990             :         int         priority;
    3991             :         int         pid;
    3992             :         WalSndState state;
    3993             :         TimestampTz replyTime;
    3994             :         bool        is_sync_standby;
    3995             :         Datum       values[PG_STAT_GET_WAL_SENDERS_COLS];
    3996       16452 :         bool        nulls[PG_STAT_GET_WAL_SENDERS_COLS] = {0};
    3997             :         int         j;
    3998             : 
    3999             :         /* Collect data from shared memory */
    4000       16452 :         SpinLockAcquire(&walsnd->mutex);
    4001       16452 :         if (walsnd->pid == 0)
    4002             :         {
    4003       14470 :             SpinLockRelease(&walsnd->mutex);
    4004       14470 :             continue;
    4005             :         }
    4006        1982 :         pid = walsnd->pid;
    4007        1982 :         sent_ptr = walsnd->sentPtr;
    4008        1982 :         state = walsnd->state;
    4009        1982 :         write = walsnd->write;
    4010        1982 :         flush = walsnd->flush;
    4011        1982 :         apply = walsnd->apply;
    4012        1982 :         writeLag = walsnd->writeLag;
    4013        1982 :         flushLag = walsnd->flushLag;
    4014        1982 :         applyLag = walsnd->applyLag;
    4015        1982 :         priority = walsnd->sync_standby_priority;
    4016        1982 :         replyTime = walsnd->replyTime;
    4017        1982 :         SpinLockRelease(&walsnd->mutex);
    4018             : 
    4019             :         /*
    4020             :          * Detect whether walsender is/was considered synchronous.  We can
    4021             :          * provide some protection against stale data by checking the PID
    4022             :          * along with walsnd_index.
    4023             :          */
    4024        1982 :         is_sync_standby = false;
    4025        2064 :         for (j = 0; j < num_standbys; j++)
    4026             :         {
    4027         136 :             if (sync_standbys[j].walsnd_index == i &&
    4028          54 :                 sync_standbys[j].pid == pid)
    4029             :             {
    4030          54 :                 is_sync_standby = true;
    4031          54 :                 break;
    4032             :             }
    4033             :         }
    4034             : 
    4035        1982 :         values[0] = Int32GetDatum(pid);
    4036             : 
    4037        1982 :         if (!has_privs_of_role(GetUserId(), ROLE_PG_READ_ALL_STATS))
    4038             :         {
    4039             :             /*
    4040             :              * Only superusers and roles with privileges of pg_read_all_stats
    4041             :              * can see details. Other users only get the pid value to know
    4042             :              * it's a walsender, but no details.
    4043             :              */
    4044           0 :             MemSet(&nulls[1], true, PG_STAT_GET_WAL_SENDERS_COLS - 1);
    4045             :         }
    4046             :         else
    4047             :         {
    4048        1982 :             values[1] = CStringGetTextDatum(WalSndGetStateString(state));
    4049             : 
    4050        1982 :             if (XLogRecPtrIsInvalid(sent_ptr))
    4051           6 :                 nulls[2] = true;
    4052        1982 :             values[2] = LSNGetDatum(sent_ptr);
    4053             : 
    4054        1982 :             if (XLogRecPtrIsInvalid(write))
    4055          18 :                 nulls[3] = true;
    4056        1982 :             values[3] = LSNGetDatum(write);
    4057             : 
    4058        1982 :             if (XLogRecPtrIsInvalid(flush))
    4059          18 :                 nulls[4] = true;
    4060        1982 :             values[4] = LSNGetDatum(flush);
    4061             : 
    4062        1982 :             if (XLogRecPtrIsInvalid(apply))
    4063          18 :                 nulls[5] = true;
    4064        1982 :             values[5] = LSNGetDatum(apply);
    4065             : 
    4066             :             /*
    4067             :              * Treat a standby such as a pg_basebackup background process
    4068             :              * which always returns an invalid flush location, as an
    4069             :              * asynchronous standby.
    4070             :              */
    4071        1982 :             priority = XLogRecPtrIsInvalid(flush) ? 0 : priority;
    4072             : 
    4073        1982 :             if (writeLag < 0)
    4074         922 :                 nulls[6] = true;
    4075             :             else
    4076        1060 :                 values[6] = IntervalPGetDatum(offset_to_interval(writeLag));
    4077             : 
    4078        1982 :             if (flushLag < 0)
    4079         726 :                 nulls[7] = true;
    4080             :             else
    4081        1256 :                 values[7] = IntervalPGetDatum(offset_to_interval(flushLag));
    4082             : 
    4083        1982 :             if (applyLag < 0)
    4084         924 :                 nulls[8] = true;
    4085             :             else
    4086        1058 :                 values[8] = IntervalPGetDatum(offset_to_interval(applyLag));
    4087             : 
    4088        1982 :             values[9] = Int32GetDatum(priority);
    4089             : 
    4090             :             /*
    4091             :              * More easily understood version of standby state. This is purely
    4092             :              * informational.
    4093             :              *
    4094             :              * In quorum-based sync replication, the role of each standby
    4095             :              * listed in synchronous_standby_names can be changing very
    4096             :              * frequently. Any standbys considered as "sync" at one moment can
    4097             :              * be switched to "potential" ones at the next moment. So, it's
    4098             :              * basically useless to report "sync" or "potential" as their sync
    4099             :              * states. We report just "quorum" for them.
    4100             :              */
    4101        1982 :             if (priority == 0)
    4102        1906 :                 values[10] = CStringGetTextDatum("async");
    4103          76 :             else if (is_sync_standby)
    4104          54 :                 values[10] = SyncRepConfig->syncrep_method == SYNC_REP_PRIORITY ?
    4105          54 :                     CStringGetTextDatum("sync") : CStringGetTextDatum("quorum");
    4106             :             else
    4107          22 :                 values[10] = CStringGetTextDatum("potential");
    4108             : 
    4109        1982 :             if (replyTime == 0)
    4110           6 :                 nulls[11] = true;
    4111             :             else
    4112        1976 :                 values[11] = TimestampTzGetDatum(replyTime);
    4113             :         }
    4114             : 
    4115        1982 :         tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
    4116             :                              values, nulls);
    4117             :     }
    4118             : 
    4119        1696 :     return (Datum) 0;
    4120             : }
    4121             : 
    4122             : /*
    4123             :  * Send a keepalive message to standby.
    4124             :  *
    4125             :  * If requestReply is set, the message requests the other party to send
    4126             :  * a message back to us, for heartbeat purposes.  We also set a flag to
    4127             :  * let nearby code know that we're waiting for that response, to avoid
    4128             :  * repeated requests.
    4129             :  *
    4130             :  * writePtr is the location up to which the WAL is sent. It is essentially
    4131             :  * the same as sentPtr but in some cases, we need to send keep alive before
    4132             :  * sentPtr is updated like when skipping empty transactions.
    4133             :  */
    4134             : static void
    4135        9948 : WalSndKeepalive(bool requestReply, XLogRecPtr writePtr)
    4136             : {
    4137        9948 :     elog(DEBUG2, "sending replication keepalive");
    4138             : 
    4139             :     /* construct the message... */
    4140        9948 :     resetStringInfo(&output_message);
    4141        9948 :     pq_sendbyte(&output_message, PqReplMsg_Keepalive);
    4142        9948 :     pq_sendint64(&output_message, XLogRecPtrIsInvalid(writePtr) ? sentPtr : writePtr);
    4143        9948 :     pq_sendint64(&output_message, GetCurrentTimestamp());
    4144        9948 :     pq_sendbyte(&output_message, requestReply ? 1 : 0);
    4145             : 
    4146             :     /* ... and send it wrapped in CopyData */
    4147        9948 :     pq_putmessage_noblock(PqMsg_CopyData, output_message.data, output_message.len);
    4148             : 
    4149             :     /* Set local flag */
    4150        9948 :     if (requestReply)
    4151        6468 :         waiting_for_ping_response = true;
    4152        9948 : }
    4153             : 
    4154             : /*
    4155             :  * Send keepalive message if too much time has elapsed.
    4156             :  */
    4157             : static void
    4158     1517656 : WalSndKeepaliveIfNecessary(void)
    4159             : {
    4160             :     TimestampTz ping_time;
    4161             : 
    4162             :     /*
    4163             :      * Don't send keepalive messages if timeouts are globally disabled or
    4164             :      * we're doing something not partaking in timeouts.
    4165             :      */
    4166     1517656 :     if (wal_sender_timeout <= 0 || last_reply_timestamp <= 0)
    4167          50 :         return;
    4168             : 
    4169     1517606 :     if (waiting_for_ping_response)
    4170       18748 :         return;
    4171             : 
    4172             :     /*
    4173             :      * If half of wal_sender_timeout has lapsed without receiving any reply
    4174             :      * from the standby, send a keep-alive message to the standby requesting
    4175             :      * an immediate reply.
    4176             :      */
    4177     1498858 :     ping_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
    4178             :                                             wal_sender_timeout / 2);
    4179     1498858 :     if (last_processing >= ping_time)
    4180             :     {
    4181           0 :         WalSndKeepalive(true, InvalidXLogRecPtr);
    4182             : 
    4183             :         /* Try to flush pending output to the client */
    4184           0 :         if (pq_flush_if_writable() != 0)
    4185           0 :             WalSndShutdown();
    4186             :     }
    4187             : }
    4188             : 
    4189             : /*
    4190             :  * Record the end of the WAL and the time it was flushed locally, so that
    4191             :  * LagTrackerRead can compute the elapsed time (lag) when this WAL location is
    4192             :  * eventually reported to have been written, flushed and applied by the
    4193             :  * standby in a reply message.
    4194             :  */
    4195             : static void
    4196      238156 : LagTrackerWrite(XLogRecPtr lsn, TimestampTz local_flush_time)
    4197             : {
    4198             :     bool        buffer_full;
    4199             :     int         new_write_head;
    4200             :     int         i;
    4201             : 
    4202      238156 :     if (!am_walsender)
    4203           0 :         return;
    4204             : 
    4205             :     /*
    4206             :      * If the lsn hasn't advanced since last time, then do nothing.  This way
    4207             :      * we only record a new sample when new WAL has been written.
    4208             :      */
    4209      238156 :     if (lag_tracker->last_lsn == lsn)
    4210      222220 :         return;
    4211       15936 :     lag_tracker->last_lsn = lsn;
    4212             : 
    4213             :     /*
    4214             :      * If advancing the write head of the circular buffer would crash into any
    4215             :      * of the read heads, then the buffer is full.  In other words, the
    4216             :      * slowest reader (presumably apply) is the one that controls the release
    4217             :      * of space.
    4218             :      */
    4219       15936 :     new_write_head = (lag_tracker->write_head + 1) % LAG_TRACKER_BUFFER_SIZE;
    4220       15936 :     buffer_full = false;
    4221       63744 :     for (i = 0; i < NUM_SYNC_REP_WAIT_MODE; ++i)
    4222             :     {
    4223       47808 :         if (new_write_head == lag_tracker->read_heads[i])
    4224           0 :             buffer_full = true;
    4225             :     }
    4226             : 
    4227             :     /*
    4228             :      * If the buffer is full, for now we just rewind by one slot and overwrite
    4229             :      * the last sample, as a simple (if somewhat uneven) way to lower the
    4230             :      * sampling rate.  There may be better adaptive compaction algorithms.
    4231             :      */
    4232       15936 :     if (buffer_full)
    4233             :     {
    4234           0 :         new_write_head = lag_tracker->write_head;
    4235           0 :         if (lag_tracker->write_head > 0)
    4236           0 :             lag_tracker->write_head--;
    4237             :         else
    4238           0 :             lag_tracker->write_head = LAG_TRACKER_BUFFER_SIZE - 1;
    4239             :     }
    4240             : 
    4241             :     /* Store a sample at the current write head position. */
    4242       15936 :     lag_tracker->buffer[lag_tracker->write_head].lsn = lsn;
    4243       15936 :     lag_tracker->buffer[lag_tracker->write_head].time = local_flush_time;
    4244       15936 :     lag_tracker->write_head = new_write_head;
    4245             : }
    4246             : 
    4247             : /*
    4248             :  * Find out how much time has elapsed between the moment WAL location 'lsn'
    4249             :  * (or the highest known earlier LSN) was flushed locally and the time 'now'.
    4250             :  * We have a separate read head for each of the reported LSN locations we
    4251             :  * receive in replies from standby; 'head' controls which read head is
    4252             :  * used.  Whenever a read head crosses an LSN which was written into the
    4253             :  * lag buffer with LagTrackerWrite, we can use the associated timestamp to
    4254             :  * find out the time this LSN (or an earlier one) was flushed locally, and
    4255             :  * therefore compute the lag.
    4256             :  *
    4257             :  * Return -1 if no new sample data is available, and otherwise the elapsed
    4258             :  * time in microseconds.
    4259             :  */
    4260             : static TimeOffset
    4261      742098 : LagTrackerRead(int head, XLogRecPtr lsn, TimestampTz now)
    4262             : {
    4263      742098 :     TimestampTz time = 0;
    4264             : 
    4265             :     /* Read all unread samples up to this LSN or end of buffer. */
    4266      787804 :     while (lag_tracker->read_heads[head] != lag_tracker->write_head &&
    4267      420844 :            lag_tracker->buffer[lag_tracker->read_heads[head]].lsn <= lsn)
    4268             :     {
    4269       45706 :         time = lag_tracker->buffer[lag_tracker->read_heads[head]].time;
    4270       45706 :         lag_tracker->last_read[head] =
    4271       45706 :             lag_tracker->buffer[lag_tracker->read_heads[head]];
    4272       45706 :         lag_tracker->read_heads[head] =
    4273       45706 :             (lag_tracker->read_heads[head] + 1) % LAG_TRACKER_BUFFER_SIZE;
    4274             :     }
    4275             : 
    4276             :     /*
    4277             :      * If the lag tracker is empty, that means the standby has processed
    4278             :      * everything we've ever sent so we should now clear 'last_read'.  If we
    4279             :      * didn't do that, we'd risk using a stale and irrelevant sample for
    4280             :      * interpolation at the beginning of the next burst of WAL after a period
    4281             :      * of idleness.
    4282             :      */
    4283      742098 :     if (lag_tracker->read_heads[head] == lag_tracker->write_head)
    4284      366960 :         lag_tracker->last_read[head].time = 0;
    4285             : 
    4286      742098 :     if (time > now)
    4287             :     {
    4288             :         /* If the clock somehow went backwards, treat as not found. */
    4289           0 :         return -1;
    4290             :     }
    4291      742098 :     else if (time == 0)
    4292             :     {
    4293             :         /*
    4294             :          * We didn't cross a time.  If there is a future sample that we
    4295             :          * haven't reached yet, and we've already reached at least one sample,
    4296             :          * let's interpolate the local flushed time.  This is mainly useful
    4297             :          * for reporting a completely stuck apply position as having
    4298             :          * increasing lag, since otherwise we'd have to wait for it to
    4299             :          * eventually start moving again and cross one of our samples before
    4300             :          * we can show the lag increasing.
    4301             :          */
    4302      706832 :         if (lag_tracker->read_heads[head] == lag_tracker->write_head)
    4303             :         {
    4304             :             /* There are no future samples, so we can't interpolate. */
    4305      337334 :             return -1;
    4306             :         }
    4307      369498 :         else if (lag_tracker->last_read[head].time != 0)
    4308             :         {
    4309             :             /* We can interpolate between last_read and the next sample. */
    4310             :             double      fraction;
    4311      295178 :             WalTimeSample prev = lag_tracker->last_read[head];
    4312      295178 :             WalTimeSample next = lag_tracker->buffer[lag_tracker->read_heads[head]];
    4313             : 
    4314      295178 :             if (lsn < prev.lsn)
    4315             :             {
    4316             :                 /*
    4317             :                  * Reported LSNs shouldn't normally go backwards, but it's
    4318             :                  * possible when there is a timeline change.  Treat as not
    4319             :                  * found.
    4320             :                  */
    4321           0 :                 return -1;
    4322             :             }
    4323             : 
    4324             :             Assert(prev.lsn < next.lsn);
    4325             : 
    4326      295178 :             if (prev.time > next.time)
    4327             :             {
    4328             :                 /* If the clock somehow went backwards, treat as not found. */
    4329           0 :                 return -1;
    4330             :             }
    4331             : 
    4332             :             /* See how far we are between the previous and next samples. */
    4333      295178 :             fraction =
    4334      295178 :                 (double) (lsn - prev.lsn) / (double) (next.lsn - prev.lsn);
    4335             : 
    4336             :             /* Scale the local flush time proportionally. */
    4337      295178 :             time = (TimestampTz)
    4338      295178 :                 ((double) prev.time + (next.time - prev.time) * fraction);
    4339             :         }
    4340             :         else
    4341             :         {
    4342             :             /*
    4343             :              * We have only a future sample, implying that we were entirely
    4344             :              * caught up but and now there is a new burst of WAL and the
    4345             :              * standby hasn't processed the first sample yet.  Until the
    4346             :              * standby reaches the future sample the best we can do is report
    4347             :              * the hypothetical lag if that sample were to be replayed now.
    4348             :              */
    4349       74320 :             time = lag_tracker->buffer[lag_tracker->read_heads[head]].time;
    4350             :         }
    4351             :     }
    4352             : 
    4353             :     /* Return the elapsed time since local flush time in microseconds. */
    4354             :     Assert(time != 0);
    4355      404764 :     return now - time;
    4356             : }

Generated by: LCOV version 1.16