From 46f198a2861e4f12636659afe7503835b768f37b Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 18 Feb 2026 17:19:43 -0500
Subject: [PATCH v14 12/12] WIP refactor

needs to be split apart and merged into previous commits.
---
 src/backend/storage/buffer/bufmgr.c   | 374 +++++++++++++-------------
 src/backend/storage/buffer/freelist.c | 374 ++++++++++++--------------
 src/include/storage/buf_internals.h   |   9 +-
 src/include/storage/bufmgr.h          |   2 +
 4 files changed, 360 insertions(+), 399 deletions(-)

diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 77bbe901f2b..76066f1d611 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -644,6 +644,11 @@ static uint32 MaxWriteBatchSize(BufferAccessStrategy strategy);
 static BlockNumber WriteBatchInit(BufferDesc *batch_start, uint32 max_batch_size,
 								  BufferWriteBatch *batch);
 static Buffer GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context);
+
+
+static void EagerCleanStrategyBuffer(BufferAccessStrategy strategy, BufferDesc *buf_hdr, IOContext io_context);
+
+static void EagerCleanBuffer(BufferAccessStrategy strategy, BufferDesc *buf_hdr, IOContext io_context);
 static void FlushUnlockedBuffer(BufferDesc *buf, SMgrRelation reln,
 								IOObject io_object, IOContext io_context);
 static void FlushBuffer(BufferDesc *buf, SMgrRelation reln,
@@ -2503,13 +2508,47 @@ MaxWriteBatchSize(BufferAccessStrategy strategy)
 	return result;
 }
 
+static BufferDesc *
+SelectVictimBuffer(BufferAccessStrategy strategy,
+				   IOContext io_context,
+				   uint64 *buf_state,
+				   void (**CleanBuffer) (BufferAccessStrategy strategy,
+										 BufferDesc *buf_hdr,
+										 IOContext io_context))
+{
+	BufferDesc *buf_hdr = NULL;
+
+	if (strategy)
+	{
+		buf_hdr = GetBufferFromRing(strategy, buf_state, io_context);
+		if (buf_hdr)
+		{
+			if (StrategySupportsEagerFlush(strategy))
+				*CleanBuffer = &EagerCleanStrategyBuffer;
+			else
+				*CleanBuffer = &EagerCleanBuffer;
+		}
+	}
+
+	/* If no strategy or didn't find a strategy buffer, get one from SB */
+	if (!buf_hdr)
+	{
+		buf_hdr = GetBufferFromClocksweep(buf_state, io_context);
+		if (strategy)
+			AddBufferToRing(strategy, buf_hdr);
+		*CleanBuffer = &EagerCleanBuffer;
+	}
+
+	CheckBufferIsPinnedOnce(BufferDescriptorGetBuffer(buf_hdr));
+	return buf_hdr;
+}
+
 static Buffer
 GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context)
 {
 	BufferDesc *buf_hdr;
-	Buffer		buf;
 	uint64		buf_state;
-	bool		from_ring;
+	Buffer		buffer;
 
 	/*
 	 * Ensure, before we pin a victim buffer, that there's a free refcount
@@ -2518,222 +2557,159 @@ GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context)
 	ReservePrivateRefCountEntry();
 	ResourceOwnerEnlarge(CurrentResourceOwner);
 
-	/* we return here if a prospective victim buffer gets used concurrently */
-again:
-
-	/*
-	 * Select a victim buffer.  The buffer is returned pinned and owned by
-	 * this backend.
-	 */
-	buf_hdr = StrategyGetBuffer(strategy, &buf_state, &from_ring);
-	buf = BufferDescriptorGetBuffer(buf_hdr);
-
-	/*
-	 * We shouldn't have any other pins for this buffer.
-	 */
-	CheckBufferIsPinnedOnce(buf);
-
-	/*
-	 * If the buffer was dirty, try to write it out.  There is a race
-	 * condition here, in that someone might dirty it after we released the
-	 * buffer header lock above, or even while we are writing it out (since
-	 * our share-lock won't prevent hint-bit updates).  We will recheck the
-	 * dirty bit after re-locking the buffer header.
-	 */
-	if (buf_state & BM_DIRTY)
+	for (;;)
 	{
-		Assert(buf_state & BM_TAG_VALID);
-		Assert(buf_state & BM_VALID);
+		void		(*CleanBuffer) (BufferAccessStrategy strategy,
+									BufferDesc *buf_hdr,
+									IOContext io_context);
 
-		/*
-		 * We need a share-lock on the buffer contents to write it out (else
-		 * we might write invalid data, eg because someone else is compacting
-		 * the page contents while we write).  We must use a conditional lock
-		 * acquisition here to avoid deadlock.  Even though the buffer was not
-		 * pinned (and therefore surely not locked) when StrategyGetBuffer
-		 * returned it, someone else could have pinned and exclusive-locked it
-		 * by the time we get here. If we try to get the lock unconditionally,
-		 * we'd block waiting for them; if they later block waiting for us,
-		 * deadlock ensues. (This has been observed to happen when two
-		 * backends are both trying to split btree index pages, and the second
-		 * one just happens to be trying to split the page the first one got
-		 * from StrategyGetBuffer.)
-		 */
-		if (!BufferLockConditional(buf, buf_hdr, BUFFER_LOCK_SHARE))
-		{
-			/*
-			 * Someone else has locked the buffer, so give it up and loop back
-			 * to get another one.
-			 */
-			UnpinBuffer(buf_hdr);
-			goto again;
-		}
+		buf_hdr = SelectVictimBuffer(strategy, io_context, &buf_state, &CleanBuffer);
 
-		/*
-		 * If using a nondefault strategy, and writing the buffer would
-		 * require a WAL flush, let the strategy decide whether to go ahead
-		 * and write/reuse the buffer or to choose another victim.  We need a
-		 * content lock to inspect the page LSN, so this can't be done inside
-		 * StrategyGetBuffer.
-		 */
-		if (strategy && StrategyRejectBuffer(strategy, buf_hdr, from_ring))
+		if (buf_state & BM_DIRTY)
 		{
-			LockBuffer(buf, BUFFER_LOCK_UNLOCK);
-			UnpinBuffer(buf_hdr);
-			goto again;
-		}
+			Assert(buf_state & BM_TAG_VALID);
+			Assert(buf_state & BM_VALID);
 
-		if (!StartBufferIO(buf_hdr, false, false))
-		{
-			/* May be nothing to do if buffer was cleaned */
-			LockBuffer(buf, BUFFER_LOCK_UNLOCK);
+			CleanBuffer(strategy, buf_hdr, io_context);
 		}
-		else if (from_ring && StrategySupportsEagerFlush(strategy))
-		{
-			BufferDesc *next_bufdesc = buf_hdr;
-			Buffer		sweep_end = buf;
-			int			cursor = StrategyGetCurrentIndex(strategy);
-			uint32		max_batch_size = MaxWriteBatchSize(strategy);
 
-			/* Pin victim again so it stays ours even after batch released */
-			ReservePrivateRefCountEntry();
-			ResourceOwnerEnlarge(CurrentResourceOwner);
-			IncrBufferRefCount(BufferDescriptorGetBuffer(buf_hdr));
+		/* Once we have a clean buffer, we're done */
+		if (!(buf_state & BM_TAG_VALID) || InvalidateVictimBuffer(buf_hdr))
+			break;
 
-			/*
-			 * Flush the victim buffer and then loop around strategy ring one
-			 * time eagerly flushing all of the eligible buffers. IO
-			 * concurrency only needs to be taken into account if AIO writes
-			 * are added in the future.
-			 */
-			for (;;)
-			{
-				bool		usage_count_zero;
-				Buffer		next_buf;
-				XLogRecPtr	next_buf_lsn;	/* unused */
+		UnpinBuffer(buf_hdr);
+	}
 
-				if (next_bufdesc)
-				{
-					BufferWriteBatch batch;
-					BlockNumber limit;
-
-					/*
-					 * After finding an eligible buffer, if we are allowed
-					 * more pins and there are more blocks in the relation,
-					 * identify any of the buffers following it which are also
-					 * eligible and combine them into a batch.
-					 *
-					 * The cursor will be advanced through the ring such that
-					 * the next write batch will start at the next eligible
-					 * buffer after the current batch ends.
-					 */
-					limit = WriteBatchInit(next_bufdesc, max_batch_size, &batch);
-					if (limit > 1)
-						FindStrategyFlushAdjacents(strategy, sweep_end,
-												   next_bufdesc,
-												   limit, &batch, &cursor);
-					FlushBufferBatch(&batch, io_context);
-					/* Pins and locks released inside CompleteWriteBatchIO */
-					CompleteWriteBatchIO(&batch, io_context, &BackendWritebackContext);
-				}
+	buffer = BufferDescriptorGetBuffer(buf_hdr);
+
+	/* a final set of sanity checks */
+#ifdef USE_ASSERT_CHECKING
+	buf_state = pg_atomic_read_u64(&buf_hdr->state);
 
-				next_buf = StrategyNextBuffer(strategy, &cursor);
+	Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 1);
+	Assert(!(buf_state & (BM_TAG_VALID | BM_VALID | BM_DIRTY)));
 
-				/* Completed one sweep of the strategy ring */
-				if (next_buf == sweep_end)
-					break;
+	CheckBufferIsPinnedOnce(buffer);
+#endif
 
-				/*
-				 * For strategies currently supporting eager flush
-				 * (BAS_BULKWRITE, eventually BAS_VACUUM), once you hit an
-				 * InvalidBuffer, the remaining buffers in the ring will be
-				 * invalid. If BAS_BULKREAD is someday supported, this logic
-				 * will have to change.
-				 */
-				if (!BufferIsValid(next_buf))
-					break;
+	return buffer;
+}
 
-				/*
-				 * If the buffer is eligible for eager flushing, it will be
-				 * the start of a new batch.  Otherwise, we'll keep looking
-				 * until we complete one full sweep around the ring.
-				 */
-				next_bufdesc =
-					PrepareOrRejectEagerFlushBuffer(next_buf,
-													NULL,
-													NULL,
-													&next_buf_lsn,
-													&usage_count_zero);
-			}
-		}
-		else
+static void
+EagerCleanBuffer(BufferAccessStrategy strategy, BufferDesc *buf_hdr, IOContext io_context)
+{
+	BufferWriteBatch batch;
+	BlockNumber limit;
+	uint32		max_batch_size = 3; /* we only look for two successors */
+	Buffer		buf = BufferDescriptorGetBuffer(buf_hdr);
+
+	if (!StartBufferIO(buf_hdr, false, false))
+	{
+		/* May be nothing to do if buffer was cleaned */
+		LockBuffer(buf, BUFFER_LOCK_UNLOCK);
+		return;
+	}
+
+	/* Pin victim again so it stays ours even after batch released */
+	ReservePrivateRefCountEntry();
+	IncrBufferRefCount(BufferDescriptorGetBuffer(buf_hdr));
+
+	/*
+	 * If we are allowed more pins and there are more blocks in the relation
+	 * and the victim buffer's block's successors are eligible for eager
+	 * flushing, combine them into a batch.
+	 */
+	limit = WriteBatchInit(buf_hdr, max_batch_size, &batch);
+	if (limit > 1)
+		FindFlushAdjacents(buf_hdr, limit, &batch);
+	FlushBufferBatch(&batch, io_context);
+	CompleteWriteBatchIO(&batch, io_context, &BackendWritebackContext);
+}
+
+static void
+EagerCleanStrategyBuffer(BufferAccessStrategy strategy, BufferDesc *buf_hdr,
+						 IOContext io_context)
+{
+	BufferDesc *next_bufdesc = buf_hdr;
+	Buffer		buf = BufferDescriptorGetBuffer(buf_hdr);
+	Buffer		sweep_end = buf;
+	int			cursor = StrategyGetCurrentIndex(strategy);
+	uint32		max_batch_size = MaxWriteBatchSize(strategy);
+
+	if (!StartBufferIO(buf_hdr, false, false))
+	{
+		/* May be nothing to do if buffer was cleaned */
+		LockBuffer(buf, BUFFER_LOCK_UNLOCK);
+		return;
+	}
+
+	/* Pin victim again so it stays ours even after batch released */
+	ReservePrivateRefCountEntry();
+	IncrBufferRefCount(BufferDescriptorGetBuffer(buf_hdr));
+
+	/*
+	 * Flush the victim buffer and then loop around strategy ring one time
+	 * eagerly flushing all of the eligible buffers. IO concurrency only needs
+	 * to be taken into account if AIO writes are added in the future.
+	 */
+	for (;;)
+	{
+		bool		usage_count_zero;
+		Buffer		next_buf;
+		XLogRecPtr	next_buf_lsn;	/* unused */
+
+		if (next_bufdesc)
 		{
 			BufferWriteBatch batch;
 			BlockNumber limit;
-			uint32		max_batch_size = 3; /* we only look for two successors */
-
-			/* Pin victim again so it stays ours even after batch released */
-			ReservePrivateRefCountEntry();
-			ResourceOwnerEnlarge(CurrentResourceOwner);
-			IncrBufferRefCount(BufferDescriptorGetBuffer(buf_hdr));
 
 			/*
-			 * If we are allowed more pins and there are more blocks in the
-			 * relation and the victim buffer's block's successors are
-			 * eligible for eager flushing, combine them into a batch.
+			 * After finding an eligible buffer, if we are allowed more pins
+			 * and there are more blocks in the relation, identify any of the
+			 * buffers following it which are also eligible and combine them
+			 * into a batch.
+			 *
+			 * The cursor will be advanced through the ring such that the next
+			 * write batch will start at the next eligible buffer after the
+			 * current batch ends.
 			 */
-			limit = WriteBatchInit(buf_hdr, max_batch_size, &batch);
+			limit = WriteBatchInit(next_bufdesc, max_batch_size, &batch);
 			if (limit > 1)
-				FindFlushAdjacents(buf_hdr, limit, &batch);
+				FindStrategyFlushAdjacents(strategy, sweep_end,
+										   next_bufdesc,
+										   limit, &batch, &cursor);
 			FlushBufferBatch(&batch, io_context);
+			/* Pins and locks released inside CompleteWriteBatchIO */
 			CompleteWriteBatchIO(&batch, io_context, &BackendWritebackContext);
 		}
-	}
 
-	if (buf_state & BM_VALID)
-	{
+		next_buf = StrategyNextBuffer(strategy, &cursor);
+
+		/* Completed one sweep of the strategy ring */
+		if (next_buf == sweep_end)
+			break;
+
 		/*
-		 * When a BufferAccessStrategy is in use, blocks evicted from shared
-		 * buffers are counted as IOOP_EVICT in the corresponding context
-		 * (e.g. IOCONTEXT_BULKWRITE). Shared buffers are evicted by a
-		 * strategy in two cases: 1) while initially claiming buffers for the
-		 * strategy ring 2) to replace an existing strategy ring buffer
-		 * because it is pinned or in use and cannot be reused.
-		 *
-		 * Blocks evicted from buffers already in the strategy ring are
-		 * counted as IOOP_REUSE in the corresponding strategy context.
-		 *
-		 * At this point, we can accurately count evictions and reuses,
-		 * because we have successfully claimed the valid buffer. Previously,
-		 * we may have been forced to release the buffer due to concurrent
-		 * pinners or erroring out.
+		 * For strategies currently supporting eager flush (BAS_BULKWRITE,
+		 * eventually BAS_VACUUM), once you hit an InvalidBuffer, the
+		 * remaining buffers in the ring will be invalid. If BAS_BULKREAD is
+		 * someday supported, this logic will have to change.
 		 */
-		pgstat_count_io_op(IOOBJECT_RELATION, io_context,
-						   from_ring ? IOOP_REUSE : IOOP_EVICT, 1, 0);
-	}
+		if (!BufferIsValid(next_buf))
+			break;
 
-	/*
-	 * If the buffer has an entry in the buffer mapping table, delete it. This
-	 * can fail because another backend could have pinned or dirtied the
-	 * buffer.
-	 */
-	if ((buf_state & BM_TAG_VALID) && !InvalidateVictimBuffer(buf_hdr))
-	{
-		UnpinBuffer(buf_hdr);
-		goto again;
+		/*
+		 * If the buffer is eligible for eager flushing, it will be the start
+		 * of a new batch.  Otherwise, we'll keep looking until we complete
+		 * one full sweep around the ring.
+		 */
+		next_bufdesc =
+			PrepareOrRejectEagerFlushBuffer(next_buf,
+											NULL,
+											NULL,
+											&next_buf_lsn,
+											&usage_count_zero);
 	}
-
-	/* a final set of sanity checks */
-#ifdef USE_ASSERT_CHECKING
-	buf_state = pg_atomic_read_u64(&buf_hdr->state);
-
-	Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 1);
-	Assert(!(buf_state & (BM_TAG_VALID | BM_VALID | BM_DIRTY)));
-
-	CheckBufferIsPinnedOnce(buf);
-#endif
-
-	return buf;
 }
 
 /*
@@ -5209,7 +5185,11 @@ FlushBufferBatch(BufferWriteBatch *batch,
 
 #ifdef USE_ASSERT_CHECKING
 	for (uint32 i = 0; i < batch->n; i++)
+	{
 		Assert(!BufferNeedsWALFlush(batch->bufdescs[i], false));
+		Assert(BufTagGetForkNum(&batch->bufdescs[i]->tag) == batch->forkno);
+		Assert(batch->bufdescs[i]->tag.blockNum == batch->start + i);
+	}
 #endif
 
 	TRACE_POSTGRESQL_BUFFER_BATCH_FLUSH_START(batch->forkno,
@@ -7227,6 +7207,20 @@ ConditionalLockBuffer(Buffer buffer)
 	return BufferLockConditional(buffer, buf, BUFFER_LOCK_EXCLUSIVE);
 }
 
+bool
+ConditionalShareLockBuffer(Buffer buffer)
+{
+	BufferDesc *buf;
+
+	Assert(BufferIsPinned(buffer));
+	if (BufferIsLocal(buffer))
+		return true;			/* act as though we got it */
+
+	buf = GetBufferDescriptor(buffer - 1);
+
+	return BufferLockConditional(buffer, buf, BUFFER_LOCK_SHARE);
+}
+
 /*
  * Verify that this backend is pinning the buffer exactly once.
  *
diff --git a/src/backend/storage/buffer/freelist.c b/src/backend/storage/buffer/freelist.c
index 9623f04b7e4..04da6b2d0fa 100644
--- a/src/backend/storage/buffer/freelist.c
+++ b/src/backend/storage/buffer/freelist.c
@@ -85,10 +85,6 @@ typedef struct BufferAccessStrategyData
 
 
 /* Prototypes for internal functions */
-static BufferDesc *GetBufferFromRing(BufferAccessStrategy strategy,
-									 uint64 *buf_state);
-static void AddBufferToRing(BufferAccessStrategy strategy,
-							BufferDesc *buf);
 
 /*
  * ClockSweepTick - Helper routine for StrategyGetBuffer()
@@ -180,156 +176,6 @@ StrategySupportsEagerFlush(BufferAccessStrategy strategy)
 	}
 }
 
-/*
- * StrategyGetBuffer
- *
- *	Called by the bufmgr to get the next candidate buffer to use in
- *	GetVictimBuffer(). The only hard requirement GetVictimBuffer() has is that
- *	the selected buffer must not currently be pinned by anyone.
- *
- *	strategy is a BufferAccessStrategy object, or NULL for default strategy.
- *
- *	It is the callers responsibility to ensure the buffer ownership can be
- *	tracked via TrackNewBufferPin().
- *
- *	The buffer is pinned and marked as owned, using TrackNewBufferPin(),
- *	before returning.
- */
-BufferDesc *
-StrategyGetBuffer(BufferAccessStrategy strategy, uint64 *buf_state, bool *from_ring)
-{
-	BufferDesc *buf;
-	int			bgwprocno;
-	int			trycounter;
-
-	*from_ring = false;
-
-	/*
-	 * If given a strategy object, see whether it can select a buffer. We
-	 * assume strategy objects don't need buffer_strategy_lock.
-	 */
-	if (strategy != NULL)
-	{
-		buf = GetBufferFromRing(strategy, buf_state);
-		if (buf != NULL)
-		{
-			*from_ring = true;
-			return buf;
-		}
-	}
-
-	/*
-	 * If asked, we need to waken the bgwriter. Since we don't want to rely on
-	 * a spinlock for this we force a read from shared memory once, and then
-	 * set the latch based on that value. We need to go through that length
-	 * because otherwise bgwprocno might be reset while/after we check because
-	 * the compiler might just reread from memory.
-	 *
-	 * This can possibly set the latch of the wrong process if the bgwriter
-	 * dies in the wrong moment. But since PGPROC->procLatch is never
-	 * deallocated the worst consequence of that is that we set the latch of
-	 * some arbitrary process.
-	 */
-	bgwprocno = INT_ACCESS_ONCE(StrategyControl->bgwprocno);
-	if (bgwprocno != -1)
-	{
-		/* reset bgwprocno first, before setting the latch */
-		StrategyControl->bgwprocno = -1;
-
-		/*
-		 * Not acquiring ProcArrayLock here which is slightly icky. It's
-		 * actually fine because procLatch isn't ever freed, so we just can
-		 * potentially set the wrong process' (or no process') latch.
-		 */
-		SetLatch(&GetPGProcByNumber(bgwprocno)->procLatch);
-	}
-
-	/*
-	 * We count buffer allocation requests so that the bgwriter can estimate
-	 * the rate of buffer consumption.  Note that buffers recycled by a
-	 * strategy object are intentionally not counted here.
-	 */
-	pg_atomic_fetch_add_u32(&StrategyControl->numBufferAllocs, 1);
-
-	/* Use the "clock sweep" algorithm to find a free buffer */
-	trycounter = NBuffers;
-	for (;;)
-	{
-		uint64		old_buf_state;
-		uint64		local_buf_state;
-
-		buf = GetBufferDescriptor(ClockSweepTick());
-
-		/*
-		 * Check whether the buffer can be used and pin it if so. Do this
-		 * using a CAS loop, to avoid having to lock the buffer header.
-		 */
-		old_buf_state = pg_atomic_read_u64(&buf->state);
-		for (;;)
-		{
-			local_buf_state = old_buf_state;
-
-			/*
-			 * If the buffer is pinned or has a nonzero usage_count, we cannot
-			 * use it; decrement the usage_count (unless pinned) and keep
-			 * scanning.
-			 */
-
-			if (BUF_STATE_GET_REFCOUNT(local_buf_state) != 0)
-			{
-				if (--trycounter == 0)
-				{
-					/*
-					 * We've scanned all the buffers without making any state
-					 * changes, so all the buffers are pinned (or were when we
-					 * looked at them). We could hope that someone will free
-					 * one eventually, but it's probably better to fail than
-					 * to risk getting stuck in an infinite loop.
-					 */
-					elog(ERROR, "no unpinned buffers available");
-				}
-				break;
-			}
-
-			/* See equivalent code in PinBuffer() */
-			if (unlikely(local_buf_state & BM_LOCKED))
-			{
-				old_buf_state = WaitBufHdrUnlocked(buf);
-				continue;
-			}
-
-			if (BUF_STATE_GET_USAGECOUNT(local_buf_state) != 0)
-			{
-				local_buf_state -= BUF_USAGECOUNT_ONE;
-
-				if (pg_atomic_compare_exchange_u64(&buf->state, &old_buf_state,
-												   local_buf_state))
-				{
-					trycounter = NBuffers;
-					break;
-				}
-			}
-			else
-			{
-				/* pin the buffer if the CAS succeeds */
-				local_buf_state += BUF_REFCOUNT_ONE;
-
-				if (pg_atomic_compare_exchange_u64(&buf->state, &old_buf_state,
-												   local_buf_state))
-				{
-					/* Found a usable buffer */
-					if (strategy != NULL)
-						AddBufferToRing(strategy, buf);
-					*buf_state = local_buf_state;
-
-					TrackNewBufferPin(BufferDescriptorGetBuffer(buf));
-
-					return buf;
-				}
-			}
-		}
-	}
-}
 
 /*
  * Returns the next buffer in the ring after the one at cursor and increments
@@ -695,6 +541,99 @@ FreeAccessStrategy(BufferAccessStrategy strategy)
 		pfree(strategy);
 }
 
+BufferDesc *
+GetBufferFromClocksweep(uint64 *buf_state, IOContext io_context)
+{
+	BufferDesc *buf;
+	Buffer		bufnum;
+	int			bgwprocno;
+	int			trycounter;
+
+	bgwprocno = INT_ACCESS_ONCE(StrategyControl->bgwprocno);
+	if (bgwprocno != -1)
+	{
+		/* reset bgwprocno first, before setting the latch */
+		StrategyControl->bgwprocno = -1;
+		SetLatch(&GetPGProcByNumber(bgwprocno)->procLatch);
+	}
+
+	pg_atomic_fetch_add_u32(&StrategyControl->numBufferAllocs, 1);
+
+	/* Use the "clock sweep" algorithm to find a free buffer */
+	trycounter = NBuffers;
+	for (;;)
+	{
+		uint64		old_buf_state;
+		uint64		local_buf_state;
+
+		buf = GetBufferDescriptor(ClockSweepTick());
+		old_buf_state = pg_atomic_read_u64(&buf->state);
+
+		for (;;)
+		{
+			local_buf_state = old_buf_state;
+
+			if (BUF_STATE_GET_REFCOUNT(local_buf_state) != 0)
+			{
+				if (--trycounter == 0)
+					elog(ERROR, "no unpinned buffers available");
+				goto next_buffer;
+			}
+
+			/* See equivalent code in PinBuffer() */
+			if (unlikely(local_buf_state & BM_LOCKED))
+			{
+				old_buf_state = WaitBufHdrUnlocked(buf);
+				continue;
+			}
+
+			if (BUF_STATE_GET_USAGECOUNT(local_buf_state) != 0)
+			{
+				local_buf_state -= BUF_USAGECOUNT_ONE;
+
+				if (pg_atomic_compare_exchange_u64(&buf->state, &old_buf_state,
+												   local_buf_state))
+				{
+					trycounter = NBuffers;
+					goto next_buffer;
+				}
+			}
+			else
+			{
+				/* pin the buffer if the CAS succeeds */
+				local_buf_state += BUF_REFCOUNT_ONE;
+
+				if (pg_atomic_compare_exchange_u64(&buf->state, &old_buf_state,
+												   local_buf_state))
+				{
+					*buf_state = local_buf_state;
+					TrackNewBufferPin(BufferDescriptorGetBuffer(buf));
+					break;
+				}
+			}
+		}
+
+		bufnum = BufferDescriptorGetBuffer(buf);
+		if (*buf_state & BM_DIRTY && !ConditionalShareLockBuffer(bufnum))
+		{
+			/*
+			 * Someone else has locked the buffer, so give it up and loop back
+			 * to get another one.
+			 */
+			ReleaseBuffer(bufnum);
+			continue;
+		}
+
+		if (*buf_state & BM_VALID)
+			pgstat_count_io_op(IOOBJECT_RELATION, io_context,
+							   IOOP_EVICT, 1, 0);
+		return buf;
+
+next_buffer:;
+	}
+}
+
+
 /*
  * GetBufferFromRing -- returns a buffer from the ring, or NULL if the
  *		ring is empty / not usable.
@@ -702,86 +641,107 @@ FreeAccessStrategy(BufferAccessStrategy strategy)
  * The buffer is pinned and marked as owned, using TrackNewBufferPin(), before
  * returning.
  */
-static BufferDesc *
-GetBufferFromRing(BufferAccessStrategy strategy, uint64 *buf_state)
+BufferDesc *
+GetBufferFromRing(BufferAccessStrategy strategy, uint64 *buf_state, IOContext io_context)
 {
 	BufferDesc *buf;
 	Buffer		bufnum;
 	uint64		old_buf_state;
 	uint64		local_buf_state;	/* to avoid repeated (de-)referencing */
 
+	Assert(strategy);
 
-	/* Advance to next ring slot */
-	if (++strategy->current >= strategy->nbuffers)
-		strategy->current = 0;
-
-	/*
-	 * If the slot hasn't been filled yet, tell the caller to allocate a new
-	 * buffer with the normal allocation strategy.  He will then fill this
-	 * slot by calling AddBufferToRing with the new buffer.
-	 */
-	bufnum = strategy->buffers[strategy->current];
-	if (bufnum == InvalidBuffer)
-		return NULL;
-
-	buf = GetBufferDescriptor(bufnum - 1);
-
-	/*
-	 * Check whether the buffer can be used and pin it if so. Do this using a
-	 * CAS loop, to avoid having to lock the buffer header.
-	 */
-	old_buf_state = pg_atomic_read_u64(&buf->state);
 	for (;;)
 	{
-		local_buf_state = old_buf_state;
+		/* Advance to next ring slot */
+		if (++strategy->current >= strategy->nbuffers)
+			strategy->current = 0;
 
 		/*
-		 * If the buffer is pinned we cannot use it under any circumstances.
-		 *
-		 * If usage_count is 0 or 1 then the buffer is fair game (we expect 1,
-		 * since our own previous usage of the ring element would have left it
-		 * there, but it might've been decremented by clock-sweep since then).
-		 * A higher usage_count indicates someone else has touched the buffer,
-		 * so we shouldn't re-use it.
+		 * If the slot hasn't been filled yet, tell the caller to allocate a
+		 * new buffer with the normal allocation strategy.  He will then fill
+		 * this slot by calling AddBufferToRing with the new buffer.
 		 */
-		if (BUF_STATE_GET_REFCOUNT(local_buf_state) != 0
-			|| BUF_STATE_GET_USAGECOUNT(local_buf_state) > 1)
-			break;
+		bufnum = strategy->buffers[strategy->current];
+		if (bufnum == InvalidBuffer)
+			return NULL;
+
+		buf = GetBufferDescriptor(bufnum - 1);
 
-		/* See equivalent code in PinBuffer() */
-		if (unlikely(local_buf_state & BM_LOCKED))
+		/*
+		 * Check whether the buffer can be used and pin it if so. Do this
+		 * using a CAS loop, to avoid having to lock the buffer header.
+		 */
+		old_buf_state = pg_atomic_read_u64(&buf->state);
+		for (;;)
 		{
-			old_buf_state = WaitBufHdrUnlocked(buf);
-			continue;
-		}
+			local_buf_state = old_buf_state;
 
-		/* pin the buffer if the CAS succeeds */
-		local_buf_state += BUF_REFCOUNT_ONE;
+			/*
+			 * If the buffer is pinned we cannot use it under any
+			 * circumstances.
+			 *
+			 * If usage_count is 0 or 1 then the buffer is fair game (we
+			 * expect 1, since our own previous usage of the ring element
+			 * would have left it there, but it might've been decremented by
+			 * clock-sweep since then). A higher usage_count indicates someone
+			 * else has touched the buffer, so we shouldn't re-use it.
+			 */
+			if (BUF_STATE_GET_REFCOUNT(local_buf_state) != 0
+				|| BUF_STATE_GET_USAGECOUNT(local_buf_state) > 1)
+				return NULL;
 
-		if (pg_atomic_compare_exchange_u64(&buf->state, &old_buf_state,
-										   local_buf_state))
-		{
-			*buf_state = local_buf_state;
+			/* See equivalent code in PinBuffer() */
+			if (unlikely(local_buf_state & BM_LOCKED))
+			{
+				old_buf_state = WaitBufHdrUnlocked(buf);
+				continue;
+			}
 
-			TrackNewBufferPin(BufferDescriptorGetBuffer(buf));
-			return buf;
+			/* pin the buffer if the CAS succeeds */
+			local_buf_state += BUF_REFCOUNT_ONE;
+
+			/* if we can't change state, keep trying */
+			if (pg_atomic_compare_exchange_u64(&buf->state, &old_buf_state,
+											   local_buf_state))
+			{
+				/* got a pin */
+				*buf_state = local_buf_state;
+				TrackNewBufferPin(BufferDescriptorGetBuffer(buf));
+				break;
+			}
 		}
-	}
 
-	/*
-	 * Tell caller to allocate a new buffer with the normal allocation
-	 * strategy.  He'll then replace this ring element via AddBufferToRing.
-	 */
-	return NULL;
+		if (*buf_state & BM_DIRTY)
+		{
+			if (!ConditionalShareLockBuffer(bufnum))
+			{
+				ReleaseBuffer(bufnum);
+				continue;
+			}
+			if (StrategyRejectBuffer(strategy, buf, true))
+			{
+				LockBuffer(bufnum, BUFFER_LOCK_UNLOCK);
+				ReleaseBuffer(bufnum);
+				continue;
+			}
+		}
+
+		if (*buf_state & BM_VALID)
+			pgstat_count_io_op(IOOBJECT_RELATION, io_context,
+							   IOOP_REUSE, 1, 0);
+		return buf;
+	}
 }
 
+
 /*
  * AddBufferToRing -- add a buffer to the buffer ring
  *
  * Caller must hold the buffer header spinlock on the buffer.  Since this
  * is called with the spinlock held, it had better be quite cheap.
  */
-static void
+void
 AddBufferToRing(BufferAccessStrategy strategy, BufferDesc *buf)
 {
 	strategy->buffers[strategy->current] = BufferDescriptorGetBuffer(buf);
diff --git a/src/include/storage/buf_internals.h b/src/include/storage/buf_internals.h
index ef5a48e7fb1..2203ce18fff 100644
--- a/src/include/storage/buf_internals.h
+++ b/src/include/storage/buf_internals.h
@@ -594,8 +594,6 @@ extern Buffer StrategyNextBuffer(BufferAccessStrategy strategy,
 								 int *cursor);
 extern int	StrategyGetCurrentIndex(BufferAccessStrategy strategy);
 extern IOContext IOContextForStrategy(BufferAccessStrategy strategy);
-extern BufferDesc *StrategyGetBuffer(BufferAccessStrategy strategy,
-									 uint64 *buf_state, bool *from_ring);
 extern bool StrategyRejectBuffer(BufferAccessStrategy strategy,
 								 BufferDesc *buf, bool from_ring);
 
@@ -641,4 +639,11 @@ extern void DropRelationLocalBuffers(RelFileLocator rlocator,
 extern void DropRelationAllLocalBuffers(RelFileLocator rlocator);
 extern void AtEOXact_LocalBuffers(bool isCommit);
 
+extern void AddBufferToRing(BufferAccessStrategy strategy, BufferDesc *buf);
+extern BufferDesc *GetBufferFromClocksweep(uint64 *buf_state, IOContext io_context);
+
+
+extern BufferDesc *GetBufferFromRing(BufferAccessStrategy strategy,
+									 uint64 *buf_state, IOContext io_context);
+
 #endif							/* BUFMGR_INTERNALS_H */
diff --git a/src/include/storage/bufmgr.h b/src/include/storage/bufmgr.h
index a40adf6b2a8..4fb68cf4266 100644
--- a/src/include/storage/bufmgr.h
+++ b/src/include/storage/bufmgr.h
@@ -334,6 +334,8 @@ LockBuffer(Buffer buffer, BufferLockMode mode)
 }
 
 extern bool ConditionalLockBuffer(Buffer buffer);
+
+extern bool ConditionalShareLockBuffer(Buffer buffer);
 extern void LockBufferForCleanup(Buffer buffer);
 extern bool ConditionalLockBufferForCleanup(Buffer buffer);
 extern bool IsBufferCleanupOK(Buffer buffer);
-- 
2.43.0

