OSDN Git Service

Fix typo.
[pg-rex/syncrep.git] / src / backend / replication / walsender.c
index 2a16888..bfcb49f 100644 (file)
  * Portions Copyright (c) 2010-2010, PostgreSQL Global Development Group
  *
  * IDENTIFICATION
- *       $PostgreSQL: pgsql/src/backend/replication/walsender.c,v 1.28 2010/07/06 19:18:57 momjian Exp $
+ *       $PostgreSQL: pgsql/src/backend/replication/walsender.c,v 1.32 2010/09/15 06:51:19 heikki Exp $
  *
  *-------------------------------------------------------------------------
  */
 #include "postgres.h"
 
+#include <signal.h>
 #include <unistd.h>
 
 #include "access/xlog_internal.h"
@@ -47,6 +48,7 @@
 #include "storage/fd.h"
 #include "storage/ipc.h"
 #include "storage/pmsignal.h"
+#include "storage/proc.h"
 #include "tcop/tcopprot.h"
 #include "utils/guc.h"
 #include "utils/memutils.h"
@@ -59,15 +61,27 @@ WalSndCtlData *WalSndCtl = NULL;
 /* My slot in the shared memory array */
 static WalSnd *MyWalSnd = NULL;
 
+/* Array of WalSndWaiter in shared memory */
+static WalSndWaiter  *WalSndWaiters;
+
 /* Global state */
 bool           am_walsender = false;           /* Am I a walsender process ? */
 
 /* User-settable parameters for walsender */
 int                    max_wal_senders = 0;    /* the maximum number of concurrent walsenders */
 int                    WalSndDelay = 200;      /* max sleep time between some actions */
+int                    replication_timeout = 0;        /* maximum time to wait for the Ack from the standby */
 
-#define NAPTIME_PER_CYCLE 100000L              /* max sleep time between cycles
-                                                                                * (100ms) */
+/*
+ * Buffer for WAL sending
+ *
+ * WalSndOutBuffer is a work area in which the output message is constructed.
+ * It's used in just so we can avoid re-palloc'ing the buffer on each cycle.
+ * It must be of size 6 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
+ */
+static char       *WalSndOutBuffer;
+static int             WalSndOutHead;          /* head of pending output */
+static int             WalSndOutTail;          /* tail of pending output */
 
 /*
  * These variables are used similarly to openLogFile/Id/Seg/Off,
@@ -84,15 +98,30 @@ static uint32 sendOff = 0;
  */
 static XLogRecPtr sentPtr = {0, 0};
 
+/*
+ * How far have we completed replication already? This is also
+ * advertised in MyWalSnd->ackdPtr. This is not used in asynchronous
+ * replication case.
+ */
+static XLogRecPtr ackdPtr = {0, 0};
+
+/* Replication mode requested by connected standby */
+static int     rplMode = REPLICATION_MODE_ASYNC;
+
 /* Flags set by signal handlers for later service in main loop */
 static volatile sig_atomic_t got_SIGHUP = false;
 static volatile sig_atomic_t shutdown_requested = false;
 static volatile sig_atomic_t ready_to_stop = false;
 
+/* Flag set by signal handler of backends for replication */
+static volatile sig_atomic_t replication_done = false;
+
 /* Signal handlers */
 static void WalSndSigHupHandler(SIGNAL_ARGS);
 static void WalSndShutdownHandler(SIGNAL_ARGS);
 static void WalSndQuickDieHandler(SIGNAL_ARGS);
+static void WalSndXLogSendHandler(SIGNAL_ARGS);
+static void WalSndLastCycleHandler(SIGNAL_ARGS);
 
 /* Prototypes for private functions */
 static int     WalSndLoop(void);
@@ -100,8 +129,13 @@ static void InitWalSnd(void);
 static void WalSndHandshake(void);
 static void WalSndKill(int code, Datum arg);
 static void XLogRead(char *buf, XLogRecPtr recptr, Size nbytes);
-static bool XLogSend(char *msgbuf, bool *caughtup);
-static void CheckClosedConnection(void);
+static bool XLogSend(bool *caughtup, bool *pending);
+static void ProcessStreamMsgs(StringInfo inMsg);
+
+static void RegisterWalSndWaiter(BackendId backendId, XLogRecPtr record,
+                                                                Latch *latch);
+static void WakeupWalSndWaiters(XLogRecPtr record);
+static XLogRecPtr GetOldestAckdPtr(void);
 
 
 /* Main entry point for walsender process */
@@ -143,6 +177,16 @@ WalSenderMain(void)
        /* Handle handshake messages before streaming */
        WalSndHandshake();
 
+       /* Initialize shared memory status */
+       {
+               /* use volatile pointer to prevent code rearrangement */
+               volatile WalSnd *walsnd = MyWalSnd;
+
+               SpinLockAcquire(&walsnd->mutex);
+               walsnd->sentPtr = sentPtr;
+               SpinLockRelease(&walsnd->mutex);
+       }
+
        /* Main loop of walsender */
        return WalSndLoop();
 }
@@ -195,6 +239,8 @@ WalSndHandshake(void)
                /* Handle the very limited subset of commands expected in this phase */
                switch (firstchar)
                {
+                       char            rplModeStr[6];
+
                        case 'Q':                       /* Query message */
                                {
                                        const char *query_string;
@@ -255,8 +301,8 @@ WalSndHandshake(void)
                                                ReadyForQuery(DestRemote);
                                                /* ReadyForQuery did pq_flush for us */
                                        }
-                                       else if (sscanf(query_string, "START_REPLICATION %X/%X",
-                                                                       &recptr.xlogid, &recptr.xrecoff) == 2)
+                                       else if (sscanf(query_string, "START_REPLICATION %X/%X MODE %5s",
+                                                                       &recptr.xlogid, &recptr.xrecoff, rplModeStr) == 3)
                                        {
                                                StringInfoData buf;
 
@@ -277,18 +323,35 @@ WalSndHandshake(void)
                                                                        (errcode(ERRCODE_CANNOT_CONNECT_NOW),
                                                                         errmsg("standby connections not allowed because wal_level=minimal")));
 
-                                               /* Send a CopyOutResponse message, and start streaming */
-                                               pq_beginmessage(&buf, 'H');
-                                               pq_sendbyte(&buf, 0);
-                                               pq_sendint(&buf, 0, 2);
+                                               /* Verify that the specified replication mode is valid */
+                                               {
+                                                       const struct config_enum_entry *entry;
+
+                                                       for (entry = replication_mode_options; entry && entry->name; entry++)
+                                                       {
+                                                               if (strcmp(rplModeStr, entry->name) == 0)
+                                                               {
+                                                                       rplMode = entry->val;
+                                                                       break;
+                                                               }
+                                                       }
+                                                       if (entry == NULL || entry->name == NULL)
+                                                               ereport(FATAL,
+                                                                               (errcode(ERRCODE_PROTOCOL_VIOLATION),
+                                                                                errmsg("invalid replication mode: %s", rplModeStr)));
+                                               }
+                                               MyWalSnd->rplMode = rplMode;
+
+                                               /* Send a CopyXLogResponse message, and start streaming */
+                                               pq_beginmessage(&buf, 'W');
                                                pq_endmessage(&buf);
                                                pq_flush();
 
                                                /*
-                                                * Initialize position to the received one, then the
+                                                * Initialize positions to the received one, then the
                                                 * xlog records begin to be shipped from that position
                                                 */
-                                               sentPtr = recptr;
+                                               sentPtr = ackdPtr = recptr;
 
                                                /* break out of the loop */
                                                replication_started = true;
@@ -322,65 +385,136 @@ WalSndHandshake(void)
 }
 
 /*
- * Check if the remote end has closed the connection.
+ * Process messages received from the standby.
+ *
+ * ereports on error.
  */
 static void
-CheckClosedConnection(void)
+ProcessStreamMsgs(StringInfo inMsg)
 {
-       unsigned char firstchar;
-       int                     r;
+       bool    acked = false;
 
-       r = pq_getbyte_if_available(&firstchar);
-       if (r < 0)
-       {
-               /* unexpected error or EOF */
-               ereport(COMMERROR,
-                               (errcode(ERRCODE_PROTOCOL_VIOLATION),
-                                errmsg("unexpected EOF on standby connection")));
-               proc_exit(0);
-       }
-       if (r == 0)
+       /* Loop to process successive complete messages available */
+       for (;;)
        {
-               /* no data available without blocking */
-               return;
-       }
+               unsigned char firstchar;
+               int                     r;
+
+               r = pq_getbyte_if_available(&firstchar);
+               if (r < 0)
+               {
+                       /* unexpected error or EOF */
+                       ereport(COMMERROR,
+                                       (errcode(ERRCODE_PROTOCOL_VIOLATION),
+                                        errmsg("unexpected EOF on standby connection")));
+                       proc_exit(0);
+               }
+               if (r == 0)
+               {
+                       /* no data available without blocking */
+                       break;
+               }
+
+               /* Handle the very limited subset of commands expected in this phase */
+               switch (firstchar)
+               {
+                       case 'd':       /* CopyData message */
+                       {
+                               unsigned char   rpltype;
+
+                               /*
+                                * Read the message contents. This is expected to be done without
+                                * blocking because we've been able to get message type code.
+                                */
+                               if (pq_getmessage(inMsg, 0))
+                                       proc_exit(0);           /* suitable message already logged */
+
+                               /* Read the replication message type from CopyData message */
+                               rpltype = pq_getmsgbyte(inMsg);
+                               switch (rpltype)
+                               {
+                                       case 'l':
+                                       {
+                                               WalAckMessageData  *msgdata;
+
+                                               msgdata = (WalAckMessageData *) pq_getmsgbytes(inMsg, sizeof(WalAckMessageData));
+
+                                               /*
+                                                * Update local status.
+                                                *
+                                                * The ackd ptr received from standby should not
+                                                * go backwards.
+                                                */
+                                               if (XLByteLE(ackdPtr, msgdata->ackEnd))
+                                                       ackdPtr = msgdata->ackEnd;
+                                               else
+                                                       ereport(FATAL,
+                                                                       (errmsg("replication completion location went back from "
+                                                                                       "%X/%X to %X/%X",
+                                                                                       ackdPtr.xlogid, ackdPtr.xrecoff,
+                                                                                       msgdata->ackEnd.xlogid, msgdata->ackEnd.xrecoff)));
+
+                                               acked = true;   /* also need to update shared position */
+                                               break;
+                                       }
+                                       default:
+                                               ereport(FATAL,
+                                                               (errcode(ERRCODE_PROTOCOL_VIOLATION),
+                                                                errmsg("invalid replication message type %d",
+                                                                               rpltype)));
+                               }
+                               break;
+                       }
 
-       /* Handle the very limited subset of commands expected in this phase */
-       switch (firstchar)
-       {
                        /*
                         * 'X' means that the standby is closing down the socket.
                         */
-               case 'X':
-                       proc_exit(0);
+                       case 'X':
+                               proc_exit(0);
 
-               default:
-                       ereport(FATAL,
-                                       (errcode(ERRCODE_PROTOCOL_VIOLATION),
-                                        errmsg("invalid standby closing message type %d",
-                                                       firstchar)));
+                       default:
+                               ereport(FATAL,
+                                               (errcode(ERRCODE_PROTOCOL_VIOLATION),
+                                                errmsg("invalid standby message type %d",
+                                                               firstchar)));
+               }
        }
+
+       if (acked)
+       {
+               /* use volatile pointer to prevent code rearrangement */
+               volatile WalSnd *walsnd = MyWalSnd;
+
+               SpinLockAcquire(&walsnd->mutex);
+               walsnd->ackdPtr = ackdPtr;
+               SpinLockRelease(&walsnd->mutex);
+       }
+
+       /* Wake up the backends that this walsender had been blocking */
+       WakeupWalSndWaiters(ackdPtr);
 }
 
 /* Main loop of walsender process */
 static int
 WalSndLoop(void)
 {
-       char       *output_message;
+       StringInfoData  input_message;
        bool            caughtup = false;
+       bool            pending = false;
+
+       initStringInfo(&input_message);
 
        /*
         * Allocate buffer that will be used for each output message.  We do this
         * just once to reduce palloc overhead.  The buffer must be made large
         * enough for maximum-sized messages.
         */
-       output_message = palloc(1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
+       WalSndOutBuffer = palloc(6 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
+       WalSndOutHead = WalSndOutTail = 0;
 
        /* Loop forever, unless we get an error */
        for (;;)
        {
-               long            remain;         /* remaining time (us) */
-
                /*
                 * Emergency bailout if postmaster has died.  This is to avoid the
                 * necessity for manual cleanup of all postmaster children.
@@ -401,9 +535,9 @@ WalSndLoop(void)
                 */
                if (ready_to_stop)
                {
-                       if (!XLogSend(output_message, &caughtup))
+                       if (!XLogSend(&caughtup, &pending))
                                break;
-                       if (caughtup)
+                       if (caughtup && !pending)
                                shutdown_requested = true;
                }
 
@@ -418,34 +552,83 @@ WalSndLoop(void)
                }
 
                /*
-                * If we had sent all accumulated WAL in last round, nap for the
-                * configured time before retrying.
-                *
-                * On some platforms, signals won't interrupt the sleep.  To ensure we
-                * respond reasonably promptly when someone signals us, break down the
-                * sleep into NAPTIME_PER_CYCLE increments, and check for interrupts
-                * after each nap.
+                * If we had sent all accumulated WAL in last round or could not
+                * flush pending WAL in output buffer because the socket was not
+                * writable, nap for the configured time before retrying.
                 */
-               if (caughtup)
+               if (caughtup || pending)
                {
-                       remain = WalSndDelay * 1000L;
-                       while (remain > 0)
+                       /*
+                        * Even if we wrote all the WAL that was available when we started
+                        * sending, more might have arrived while we were sending this
+                        * batch. We had the latch set while sending, so we have not
+                        * received any signals from that time. Let's arm the latch
+                        * again, and after that check that we're still up-to-date.
+                        */
+                       ResetLatch(&MyWalSnd->latch);
+
+                       if (!XLogSend(&caughtup, &pending))
+                               break;
+                       if ((caughtup || pending) && !got_SIGHUP && !ready_to_stop &&
+                               !shutdown_requested)
                        {
-                               /* Check for interrupts */
-                               if (got_SIGHUP || shutdown_requested || ready_to_stop)
-                                       break;
+                               bool            check_timeout;
+                               long            sleeptime;
+                               int                     res;
+
+                               /*
+                                * XXX: We don't really need the periodic wakeups anymore,
+                                * WaitLatchOrSocket should reliably wake up as soon as
+                                * something interesting happens.
+                                */
 
-                               /* Sleep and check that the connection is still alive */
-                               pg_usleep(remain > NAPTIME_PER_CYCLE ? NAPTIME_PER_CYCLE : remain);
-                               CheckClosedConnection();
+                               /*
+                                * Check for replication timeout if it's enabled and we need
+                                * to wait until the socket has become writable to flush
+                                * pending WAL in output buffer or until the Ack message
+                                * from the standby has become available.
+                                */
+                               if (replication_timeout > 0 &&
+                                       (pending ||
+                                        (rplMode != REPLICATION_MODE_ASYNC &&
+                                         XLByteLT(ackdPtr, sentPtr))))
+                               {
+                                       sleeptime = replication_timeout;
+                                       check_timeout = true;
+                               }
+                               else
+                               {
+                                       sleeptime = WalSndDelay;
+                                       check_timeout = false;
+                               }
+
+                               /* Sleep */
+                               res = WaitLatchOrSocket(&MyWalSnd->latch, MyProcPort->sock,
+                                                                               true, (WalSndOutTail > 0),
+                                                                               sleeptime * 1000L);
 
-                               remain -= NAPTIME_PER_CYCLE;
+                               if (res == 0 && check_timeout)
+                               {
+                                       /*
+                                        * Since typically expiration of replication timeout means
+                                        * communication problem, we don't send the error message
+                                        * to the standby.
+                                        */
+                                       ereport(COMMERROR,
+                                                       (errmsg("terminating walsender process due to replication timeout")));
+                                       break;
+                               }
                        }
-               }
 
-               /* Attempt to send the log once every loop */
-               if (!XLogSend(output_message, &caughtup))
-                       break;
+                       /* Process messages received from the standby */
+                       ProcessStreamMsgs(&input_message);
+               }
+               else
+               {
+                       /* Attempt to send the log once every loop */
+                       if (!XLogSend(&caughtup, &pending))
+                               break;
+               }
        }
 
        /*
@@ -492,11 +675,17 @@ InitWalSnd(void)
                }
                else
                {
-                       /* found */
-                       MyWalSnd = (WalSnd *) walsnd;
+                       /*
+                        * Found a free slot. Reserve it for us.
+                        */
                        walsnd->pid = MyProcPid;
-                       MemSet(&MyWalSnd->sentPtr, 0, sizeof(XLogRecPtr));
+                       MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
+                       MemSet(&walsnd->ackdPtr, 0, sizeof(XLogRecPtr));
                        SpinLockRelease(&walsnd->mutex);
+                       /* don't need the lock anymore */
+                       OwnLatch((Latch *) &walsnd->latch);
+                       MyWalSnd = (WalSnd *) walsnd;
+
                        break;
                }
        }
@@ -517,11 +706,16 @@ WalSndKill(int code, Datum arg)
 {
        Assert(MyWalSnd != NULL);
 
+       /* Wake up the backends that this walsender had been blocking */
+       MyWalSnd->rplMode = REPLICATION_MODE_ASYNC;
+       WakeupWalSndWaiters(GetOldestAckdPtr());
+
        /*
         * Mark WalSnd struct no longer in use. Assume that no lock is required
         * for this.
         */
        MyWalSnd->pid = 0;
+       DisownLatch(&MyWalSnd->latch);
 
        /* WalSnd struct isn't mine anymore */
        MyWalSnd = NULL;
@@ -646,24 +840,48 @@ XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
  * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
  * but not yet sent to the client, and send it.
  *
- * msgbuf is a work area in which the output message is constructed.  It's
- * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
- * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
- *
  * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
  * *caughtup is set to false.
  *
+ * If there is pending WAL in output buffer, *pending is set to true,
+ * otherwise *pending is set to false.
+ *
  * Returns true if OK, false if trouble.
  */
 static bool
-XLogSend(char *msgbuf, bool *caughtup)
+XLogSend(bool *caughtup, bool *pending)
 {
        XLogRecPtr      SendRqstPtr;
        XLogRecPtr      startptr;
-       XLogRecPtr      endptr;
+       static XLogRecPtr       endptr;
        Size            nbytes;
+       uint32          n32;
+       int                     res;
        WalDataMessageHeader msghdr;
 
+       /* Attempt to flush pending WAL in output buffer */
+       if (*pending)
+       {
+               if (WalSndOutHead != WalSndOutTail)
+               {
+                       res = pq_putbytes_if_writable(WalSndOutBuffer + WalSndOutHead,
+                                                                                 WalSndOutTail - WalSndOutHead);
+                       if (res == EOF)
+                               return false;
+                       WalSndOutHead += res;
+                       if (WalSndOutHead != WalSndOutTail)
+                               return true;
+               }
+
+               res = pq_flush_if_writable();
+               if (res == EOF)
+                       return false;
+               if (res == 0)
+                       return true;
+
+               goto updt;
+       }
+
        /*
         * Attempt to send all data that's already been written out and fsync'd to
         * disk.  We cannot go further than what's been written out given the
@@ -732,13 +950,19 @@ XLogSend(char *msgbuf, bool *caughtup)
        /*
         * OK to read and send the slice.
         */
-       msgbuf[0] = 'w';
+       WalSndOutBuffer[0] = 'd';
+       WalSndOutBuffer[5] = 'w';
+       WalSndOutHead = 0;
+       WalSndOutTail = 6 + sizeof(WalDataMessageHeader) + nbytes;
+
+       n32 = htonl((uint32) WalSndOutTail - 1);
+       memcpy(WalSndOutBuffer + 1, &n32, 4);
 
        /*
         * Read the log directly into the output buffer to avoid extra memcpy
         * calls.
         */
-       XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
+       XLogRead(WalSndOutBuffer + 6 + sizeof(WalDataMessageHeader), startptr, nbytes);
 
        /*
         * We fill the message header last so that the send timestamp is taken as
@@ -748,13 +972,34 @@ XLogSend(char *msgbuf, bool *caughtup)
        msghdr.walEnd = SendRqstPtr;
        msghdr.sendTime = GetCurrentTimestamp();
 
-       memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
+       memcpy(WalSndOutBuffer + 6, &msghdr, sizeof(WalDataMessageHeader));
 
-       pq_putmessage('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
+       res = pq_putbytes_if_writable(WalSndOutBuffer, WalSndOutTail);
+       if (res == EOF)
+               return false;
+
+       WalSndOutHead = res;
+       if (WalSndOutHead != WalSndOutTail)
+       {
+               *caughtup = false;
+               *pending = true;
+               return true;
+       }
 
        /* Flush pending output to the client */
-       if (pq_flush())
+       res = pq_flush_if_writable();
+       if (res == EOF)
                return false;
+       if (res == 0)
+       {
+               *caughtup = false;
+               *pending = true;
+               return true;
+       }
+
+updt:
+       WalSndOutHead = WalSndOutTail = 0;
+       *pending = false;
 
        sentPtr = endptr;
 
@@ -786,6 +1031,8 @@ static void
 WalSndSigHupHandler(SIGNAL_ARGS)
 {
        got_SIGHUP = true;
+       if (MyWalSnd)
+               SetLatch(&MyWalSnd->latch);
 }
 
 /* SIGTERM: set flag to shut down */
@@ -793,6 +1040,8 @@ static void
 WalSndShutdownHandler(SIGNAL_ARGS)
 {
        shutdown_requested = true;
+       if (MyWalSnd)
+               SetLatch(&MyWalSnd->latch);
 }
 
 /*
@@ -827,11 +1076,20 @@ WalSndQuickDieHandler(SIGNAL_ARGS)
        exit(2);
 }
 
+/* SIGUSR1: set flag to send WAL records */
+static void
+WalSndXLogSendHandler(SIGNAL_ARGS)
+{
+       latch_sigusr1_handler();
+}
+
 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
 static void
 WalSndLastCycleHandler(SIGNAL_ARGS)
 {
        ready_to_stop = true;
+       if (MyWalSnd)
+               SetLatch(&MyWalSnd->latch);
 }
 
 /* Set up signal handlers */
@@ -846,7 +1104,7 @@ WalSndSignals(void)
        pqsignal(SIGQUIT, WalSndQuickDieHandler);       /* hard crash time */
        pqsignal(SIGALRM, SIG_IGN);
        pqsignal(SIGPIPE, SIG_IGN);
-       pqsignal(SIGUSR1, SIG_IGN); /* not used */
+       pqsignal(SIGUSR1, WalSndXLogSendHandler);       /* request WAL sending */
        pqsignal(SIGUSR2, WalSndLastCycleHandler);      /* request a last cycle and
                                                                                                 * shutdown */
 
@@ -867,6 +1125,13 @@ WalSndShmemSize(void)
        size = offsetof(WalSndCtlData, walsnds);
        size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
 
+       /*
+        * If replication is enabled, we have a data structure called
+        * WalSndWaiters, created in shared memory.
+        */
+       if (max_wal_senders > 0)
+               size = add_size(size, mul_size(MaxBackends, sizeof(WalSndWaiter)));
+
        return size;
 }
 
@@ -876,54 +1141,243 @@ WalSndShmemInit(void)
 {
        bool            found;
        int                     i;
+       Size            size = add_size(offsetof(WalSndCtlData, walsnds),
+                                                               mul_size(max_wal_senders, sizeof(WalSnd)));
 
        WalSndCtl = (WalSndCtlData *)
-               ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
+               ShmemInitStruct("Wal Sender Ctl", size, &found);
 
        if (!found)
        {
                /* First time through, so initialize */
-               MemSet(WalSndCtl, 0, WalSndShmemSize());
+               MemSet(WalSndCtl, 0, size);
 
                for (i = 0; i < max_wal_senders; i++)
                {
                        WalSnd     *walsnd = &WalSndCtl->walsnds[i];
 
                        SpinLockInit(&walsnd->mutex);
+                       InitSharedLatch(&walsnd->latch);
+               }
+       }
+
+       /* Create or attach to the WalSndWaiters array too, if needed */
+       if (max_wal_senders > 0)
+       {
+               WalSndWaiters = (WalSndWaiter *)
+                       ShmemInitStruct("WalSndWaiters",
+                                                       mul_size(MaxBackends, sizeof(WalSndWaiter)),
+                                                       &found);
+               WalSndCtl->maxWaiters = MaxBackends;
+       }
+}
+
+/* Wake up all walsenders */
+void
+WalSndWakeup(void)
+{
+       int             i;
+
+       for (i = 0; i < max_wal_senders; i++)
+               SetLatch(&WalSndCtl->walsnds[i].latch);
+}
+
+/*
+ * Ensure that replication has been completed up to the given position.
+ */
+void
+WaitXLogSend(XLogRecPtr record)
+{
+       int             i;
+       bool    mustwait = false;
+
+       Assert(max_wal_senders > 0);
+
+       for (i = 0; i < max_wal_senders; i++)
+       {
+               /* use volatile pointer to prevent code rearrangement */
+               volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
+               XLogRecPtr              recptr;
+
+               /* Don't need to wait for asynchronous walsender */
+               if (walsnd->pid == 0 ||
+                       walsnd->rplMode <= REPLICATION_MODE_ASYNC)
+                       continue;
+
+               SpinLockAcquire(&walsnd->mutex);
+               recptr = walsnd->ackdPtr;
+               SpinLockRelease(&walsnd->mutex);
+
+               if (recptr.xlogid == 0 && recptr.xrecoff == 0)
+                       continue;
+
+               /* Quick exit if already known replicated */
+               if (XLByteLE(record, recptr))
+                       return;
+
+               mustwait = true;
+       }
+
+       /*
+        * Don't need to wait for replication if there is no synchronous
+        * standby
+        */
+       if (!mustwait)
+               return;
+
+       /*
+        * Register myself into the wait list and sleep until replication
+        * has been completed up to the given position and the walsender
+        * signals me.
+        *
+        * If replication has been completed up to the latest position
+        * before the registration, walsender might be unable to send the
+        * signal immediately. We must wake up the walsender after the
+        * registration.
+        */
+       ResetLatch(&MyProc->latch);
+       RegisterWalSndWaiter(MyBackendId, record, &MyProc->latch);
+       WalSndWakeup();
+
+       for (;;)
+       {
+               WaitLatch(&MyProc->latch, 1000000L);
+
+               /* If done already, we finish waiting */
+               if (replication_done)
+               {
+                       replication_done = false;
+                       return;
                }
        }
 }
 
 /*
- * This isn't currently used for anything. Monitoring tools might be
- * interested in the future, and we'll need something like this in the
- * future for synchronous replication.
+ * Register the given backend into the wait list.
  */
-#ifdef NOT_USED
+static void
+RegisterWalSndWaiter(BackendId backendId, XLogRecPtr record, Latch *latch)
+{
+       /* use volatile pointer to prevent code rearrangement */
+       volatile WalSndCtlData  *walsndctl = WalSndCtl;
+       int             i;
+       int             count = 0;
+
+       LWLockAcquire(WalSndWaiterLock, LW_EXCLUSIVE);
+
+       /* Out of slots. This should not happen. */
+       if (walsndctl->numWaiters + 1 > walsndctl->maxWaiters)
+               elog(PANIC, "out of replication waiters slots");
+
+       /*
+        * The given position is expected to be relatively new in the
+        * wait list. Since the entries in the list are sorted in an
+        * increasing order of XLogRecPtr, we can shorten the time it
+        * takes to find an insert slot by scanning the list backwards.
+        */
+       for (i = walsndctl->numWaiters; i > 0; i--)
+       {
+               if (XLByteLE(WalSndWaiters[i - 1].record, record))
+                       break;
+               count++;
+       }
+
+       /* Shuffle the list if needed */
+       if (count > 0)
+               memmove(&WalSndWaiters[i + 1], &WalSndWaiters[i],
+                               count * sizeof(WalSndWaiter));
+
+       WalSndWaiters[i].backendId = backendId;
+       WalSndWaiters[i].record = record;
+       WalSndWaiters[i].latch = latch;
+       walsndctl->numWaiters++;
+
+       LWLockRelease(WalSndWaiterLock);
+}
+
+/*
+ * Wake up the backends waiting until replication has been completed
+ * up to the position older than or equal to the given one.
+ *
+ * Wake up all waiters if InvalidXLogRecPtr is given.
+   */
+static void
+WakeupWalSndWaiters(XLogRecPtr record)
+{
+       /* use volatile pointer to prevent code rearrangement */
+       volatile WalSndCtlData  *walsndctl = WalSndCtl;
+       int             i;
+       int             count = 0;
+       bool    all_wakeup = (record.xlogid == 0 && record.xrecoff == 0);
+
+       LWLockAcquire(WalSndWaiterLock, LW_EXCLUSIVE);
+
+       for (i = 0; i < walsndctl->numWaiters; i++)
+       {
+               /* use volatile pointer to prevent code rearrangement */
+               volatile WalSndWaiter  *waiter = &WalSndWaiters[i];
+
+               if (all_wakeup || XLByteLE(waiter->record, record))
+               {
+                       SetProcLatch(waiter->latch, PROCSIG_REPLICATION_INTERRUPT,
+                                                waiter->backendId);
+                       count++;
+               }
+               else
+               {
+                       /*
+                        * If the backend waiting for the Ack position newer than
+                        * the given one is found, we don't need to search the wait
+                        * list any more. This is because the waiters in the list
+                        * are guaranteed to be sorted in an increasing order of
+                        * XLogRecPtr.
+                        */
+                       break;
+               }
+       }
+
+       /* If there are still some waiters, left-justify them in the list */
+       walsndctl->numWaiters -= count;
+       if (walsndctl->numWaiters > 0 && count > 0)
+               memmove(&WalSndWaiters[0], &WalSndWaiters[i],
+                               walsndctl->numWaiters * sizeof(WalSndWaiter));
+
+       LWLockRelease(WalSndWaiterLock);
+}
+
 /*
- * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
- * if none.
+ * Returns the oldest Ack position in synchronous walsenders. Or
+ * InvalidXLogRecPtr if none.
  */
-XLogRecPtr
-GetOldestWALSendPointer(void)
+static XLogRecPtr
+GetOldestAckdPtr(void)
 {
        XLogRecPtr      oldest = {0, 0};
-       int                     i;
-       bool            found = false;
+       int             i;
+       bool    found = false;
 
        for (i = 0; i < max_wal_senders; i++)
        {
                /* use volatile pointer to prevent code rearrangement */
                volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
-               XLogRecPtr      recptr;
+               XLogRecPtr              recptr;
 
-               if (walsnd->pid == 0)
+               /*
+                * Ignore the Ack position that asynchronous walsender has
+                * since it has never received any Ack.
+                */
+               if (walsnd->pid == 0 ||
+                       walsnd->rplMode <= REPLICATION_MODE_ASYNC)
                        continue;
 
                SpinLockAcquire(&walsnd->mutex);
-               recptr = walsnd->sentPtr;
+               recptr = walsnd->ackdPtr;
                SpinLockRelease(&walsnd->mutex);
 
+               /*
+                * Ignore the Ack position that the walsender which has not
+                * received any Ack yet has.
+                */
                if (recptr.xlogid == 0 && recptr.xrecoff == 0)
                        continue;
 
@@ -934,4 +1388,11 @@ GetOldestWALSendPointer(void)
        return oldest;
 }
 
-#endif
+/*
+ * This is called when PROCSIG_REPLICATION_INTERRUPT is received.
+ */
+void
+HandleReplicationInterrupt(void)
+{
+       replication_done = true;
+}