>From 29b1954f4bba9ffd7e28fac1c8c4302dfe4bc2a6 Mon Sep 17 00:00:00 2001
From: Takashi Menjo <takashi.menjou.vg@hco.ntt.co.jp>
Date: Mon, 10 Feb 2020 17:53:14 +0900
Subject: [msync 3/5] Lazy-unmap WAL segments

---
 src/backend/access/transam/xlog.c | 28 ++++++++++++++++++++++++++--
 1 file changed, 26 insertions(+), 2 deletions(-)

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 43f9a8affc..317816a0b9 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -768,7 +768,9 @@ static const char *xlogSourceNames[] = {"any", "archive", "pg_wal", "stream"};
  */
 static int	openLogFile = -1;
 static XLogSegNo openLogSegNo = 0;
+static XLogSegNo beingClosedLogSegNo = 0;
 static char *mappedPages = NULL;
+static char *beingUnmappedPages = NULL;
 static bool pmemMapped = 0;
 
 /*
@@ -1162,6 +1164,14 @@ XLogInsertRecord(XLogRecData *rdata,
 		}
 	}
 
+	/* Lazy-unmap */
+	if (beingUnmappedPages != NULL)
+	{
+		XLogFileUnmap(beingUnmappedPages, beingClosedLogSegNo);
+		beingUnmappedPages = NULL;
+		beingClosedLogSegNo = 0;
+	}
+
 #ifdef WAL_DEBUG
 	if (XLOG_DEBUG)
 	{
@@ -1794,9 +1804,23 @@ GetXLogBuffer(XLogRecPtr ptr)
 	XLByteToSeg(ptr, segno, wal_segment_size);
 	if (segno != openLogSegNo)
 	{
-		/* Unmap the current segment if mapped */
+		/*
+		 * We do not want to unmap the current segment here because we are in
+		 * a critial section and unmap is time-consuming operation.  So we
+		 * just mark it to be unmapped later.
+		 */
 		if (mappedPages != NULL)
-			XLogFileUnmap(mappedPages, openLogSegNo);
+		{
+			/*
+			 * If there is another being-unmapped segment, it cannot be helped;
+			 * we unmap it here.
+			 */
+			if (beingUnmappedPages != NULL)
+				XLogFileUnmap(beingUnmappedPages, beingClosedLogSegNo);
+
+			beingUnmappedPages = mappedPages;
+			beingClosedLogSegNo = openLogSegNo;
+		}
 
 		/* Map the segment we need */
 		mappedPages = XLogFileMap(segno, &pmemMapped);
-- 
2.20.1

