From 690f7e81f8a5e5a6539e4e8d530834cd4f032960 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 3 Jun 2026 18:08:16 -0400
Subject: [PATCH v17 17/21] Add bgwriter helper to write buffers

BgBufferSync() is long and complex. Put the logic that actually cleans
the number of buffers it has decided to clean in its own helper. This is
useful for code clarity, but it also allows us to test the upcoming
bgwriter write combining logic. It's very difficult to directly test any
bgwriter functionality reliably.
---
 src/backend/storage/buffer/bufmgr.c | 139 ++++++++++++++++++----------
 src/include/storage/buf_internals.h |   4 +
 2 files changed, 92 insertions(+), 51 deletions(-)

diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 82c50550861..912cff514b1 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -4130,6 +4130,87 @@ CheckPointBuffers(int flags)
 	TRACE_POSTGRESQL_BUFFER_SYNC_DONE(NBuffers, num_written, num_to_scan);
 }
 
+/*
+ * Clean dirty reusable buffers.
+ *
+ * This is the bgwriter's LRU cleaning scan. It works forward from
+ * next_to_clean and stops after scanning num_to_scan buffers, finding enough
+ * reusable buffers, or hitting lru_maxpages. BgBufferSync() is long and
+ * complicated, so this helps simplify it. It also allows us to directly test
+ * background writer write combining logic.
+ */
+int
+BgwriterWriteBuffers(int lru_maxpages, WritebackContext *wb_context,
+					 int *next_to_clean, uint32 *next_passes,
+					 int *num_to_scan, int *reusable_buffers,
+					 int upcoming_alloc_est, bool *maxwritten_clean)
+{
+	int			num_written = 0;
+	int			to_scan = *num_to_scan;
+	int			reusable = *reusable_buffers;
+
+	*maxwritten_clean = false;
+
+	/* Execute the LRU scan */
+	while (to_scan > 0 && reusable < upcoming_alloc_est)
+	{
+		uint64		buf_state;
+		BufferDesc *bufHdr;
+		BufferTag	tag;
+
+		/* Reserve space for the pin before taking the header lock. */
+		ReservePrivateRefCountEntry();
+		ResourceOwnerEnlarge(CurrentResourceOwner);
+
+		/* Advance the saved cursor even if writing this buffer later fails */
+		bufHdr = GetBufferDescriptor(*next_to_clean);
+		to_scan--;
+		if (++(*next_to_clean) >= NBuffers)
+		{
+			*next_to_clean = 0;
+			(*next_passes)++;
+		}
+
+		buf_state = LockBufHdr(bufHdr);
+		if (BUF_STATE_GET_REFCOUNT(buf_state) != 0 ||
+			BUF_STATE_GET_USAGECOUNT(buf_state) != 0)
+		{
+			UnlockBufHdr(bufHdr);
+			continue;
+		}
+
+		reusable++;
+
+		if (!(buf_state & BM_VALID) || !(buf_state & BM_DIRTY))
+		{
+			UnlockBufHdr(bufHdr);
+			continue;
+		}
+
+		/* Pin the selected buffer and release the header lock. */
+		PinBuffer_Locked(bufHdr);
+
+		FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
+
+		/* Snapshot the tag before unpinning */
+		tag = bufHdr->tag;
+		UnpinBuffer(bufHdr);
+
+		ScheduleBufferTagForWriteback(wb_context, IOCONTEXT_NORMAL, &tag);
+
+		if (++num_written >= lru_maxpages)
+		{
+			*maxwritten_clean = true;
+			break;
+		}
+	}
+
+	*num_to_scan = to_scan;
+	*reusable_buffers = reusable;
+
+	return num_written;
+}
+
 /*
  * BgBufferSync -- Write out some dirty buffers in the pool.
  *
@@ -4180,6 +4261,7 @@ BgBufferSync(WritebackContext *wb_context)
 	int			num_to_scan;
 	int			num_written;
 	int			reusable_buffers;
+	bool		maxwritten_clean;
 
 	/* Variables for final smoothed_density update */
 	long		new_strategy_delta;
@@ -4361,58 +4443,13 @@ BgBufferSync(WritebackContext *wb_context)
 	num_written = 0;
 	reusable_buffers = reusable_buffers_est;
 
-	/* Execute the LRU scan */
-	while (num_to_scan > 0 && reusable_buffers < upcoming_alloc_est)
-	{
-		uint64		buf_state;
-		BufferDesc *bufHdr;
-		BufferTag	tag;
-
-		/* Reserve space for the pin before taking the header lock. */
-		ReservePrivateRefCountEntry();
-		ResourceOwnerEnlarge(CurrentResourceOwner);
-
-		bufHdr = GetBufferDescriptor(next_to_clean);
-		num_to_scan--;
-		if (++next_to_clean >= NBuffers)
-		{
-			next_to_clean = 0;
-			next_passes++;
-		}
+	num_written = BgwriterWriteBuffers(bgwriter_lru_maxpages, wb_context,
+									   &next_to_clean, &next_passes,
+									   &num_to_scan, &reusable_buffers,
+									   upcoming_alloc_est, &maxwritten_clean);
 
-		buf_state = LockBufHdr(bufHdr);
-		if (BUF_STATE_GET_REFCOUNT(buf_state) != 0 ||
-			BUF_STATE_GET_USAGECOUNT(buf_state) != 0)
-		{
-			UnlockBufHdr(bufHdr);
-			continue;
-		}
-
-		reusable_buffers++;
-
-		if (!(buf_state & BM_VALID) || !(buf_state & BM_DIRTY))
-		{
-			UnlockBufHdr(bufHdr);
-			continue;
-		}
-
-		/* Pin the selected buffer and release the header lock. */
-		PinBuffer_Locked(bufHdr);
-
-		FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
-
-		/* Snapshot the tag before unpinning */
-		tag = bufHdr->tag;
-		UnpinBuffer(bufHdr);
-
-		ScheduleBufferTagForWriteback(wb_context, IOCONTEXT_NORMAL, &tag);
-
-		if (++num_written >= bgwriter_lru_maxpages)
-		{
-			PendingBgWriterStats.maxwritten_clean++;
-			break;
-		}
-	}
+	if (maxwritten_clean)
+		PendingBgWriterStats.maxwritten_clean++;
 
 	PendingBgWriterStats.buf_written_clean += num_written;
 
diff --git a/src/include/storage/buf_internals.h b/src/include/storage/buf_internals.h
index 45260ecff60..c49867584b3 100644
--- a/src/include/storage/buf_internals.h
+++ b/src/include/storage/buf_internals.h
@@ -599,6 +599,10 @@ extern void TerminateBufferIO(BufferDesc *buf, bool clear_dirty, uint64 set_flag
 
 extern void WriteBufferAndNeighbors(Buffer bufnum, BufferDesc *buf_hdr, IOContext io_context,
 									WritebackContext *wb_context);
+extern int	BgwriterWriteBuffers(int lru_maxpages, WritebackContext *wb_context,
+								 int *next_to_clean, uint32 *next_passes,
+								 int *num_to_scan, int *reusable_buffers,
+								 int upcoming_alloc_est, bool *maxwritten_clean);
 
 
 /* freelist.c */
-- 
2.43.0

