From 0512c840432995b9c8968c7561b5575ee2ff4f51 Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Date: Fri, 25 Oct 2019 12:07:52 +0900
Subject: [PATCH v22 3/5] Fix MarkBufferDirtyHint

---
 src/backend/catalog/storage.c       | 22 ++++++++++++++++++++++
 src/backend/storage/buffer/bufmgr.c |  5 ++++-
 src/include/catalog/storage.h       |  1 +
 3 files changed, 27 insertions(+), 1 deletion(-)

diff --git a/src/backend/catalog/storage.c b/src/backend/catalog/storage.c
index 806f235..5e54b62 100644
--- a/src/backend/catalog/storage.c
+++ b/src/backend/catalog/storage.c
@@ -441,6 +441,28 @@ RelationCopyStorage(SMgrRelation src, SMgrRelation dst,
 }
 
 /*
+ * RelFileNodeSkippingWAL - check if WAL-logging is allows for the relfilenode
+ *
+ *   When wal_level is minimal, we skip WAL-logging for permanent relations
+ *   created in the current transaction. Changes of such relfilenodes shoudn't
+ *   be WAL-logged. Though it is known from Relation efficiently, thisfunction
+ *   is intended for the code paths not having access to Relation.
+ */
+bool
+RelFileNodeSkippingWAL(RelFileNode rnode)
+{
+	PendingRelOp *pending;
+
+	for (pending = pendingSyncs ; pending != NULL ; pending = pending->next)
+	{
+		if (RelFileNodeEquals(pending->relnode, rnode))
+			return true;
+	}
+
+	return false;
+}
+
+/*
  *	smgrDoPendingDeletes() -- Take care of relation deletes at end of xact.
  *
  * This also runs when aborting a subxact; we want to clean up a failed
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 827626b..9065d55 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -3492,9 +3492,12 @@ MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
 		 *
 		 * We don't check full_page_writes here because that logic is included
 		 * when we call XLogInsert() since the value changes dynamically.
+		 *
+		 * We mustn't emit WAL for WAL-skipping relations.
 		 */
 		if (XLogHintBitIsNeeded() &&
-			(pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT))
+			(pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT) &&
+			!RelFileNodeSkippingWAL(bufHdr->tag.rnode))
 		{
 			/*
 			 * If we're in recovery we cannot dirty a page because of a hint.
diff --git a/src/include/catalog/storage.h b/src/include/catalog/storage.h
index 24e7165..eb2666e 100644
--- a/src/include/catalog/storage.h
+++ b/src/include/catalog/storage.h
@@ -35,6 +35,7 @@ extern void RelationPreserveStorage(RelFileNode rnode, bool atCommit);
 extern void RelationTruncate(Relation rel, BlockNumber nblocks);
 extern void RelationCopyStorage(SMgrRelation src, SMgrRelation dst,
 								ForkNumber forkNum, char relpersistence);
+extern bool RelFileNodeSkippingWAL(RelFileNode rnode);
 
 /*
  * These functions used to be in storage/smgr/smgr.c, which explains the
-- 
2.9.2

