From ff29856d80c1c3778cc99a35ed8f2ba8c642d37f Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Wed, 9 Apr 2025 15:16:31 +1200
Subject: [PATCH v2 2/4] Improve read_stream.c program flow.

Commit 55918f79 removed the space-based reason for calling
read_stream_look_ahead() at the top and bottom of
read_stream_next_buffer().

Commit 7ea8cd15 removed the need to call it with a different flag in
each spot.

We can delete a couple of dozen lines and just call it at the top now.
That's much tidier, but also required for a later patch that reorders
the queue.
---
 src/backend/storage/aio/read_stream.c | 29 +++++----------------------
 1 file changed, 5 insertions(+), 24 deletions(-)

diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 0d3dd65bfed..a98213d4df2 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -909,28 +909,12 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	}
 #endif
 
-	if (unlikely(stream->pinned_buffers == 0))
+	/* Look ahead and check for end of stream. */
+	read_stream_look_ahead(stream);
+	if (stream->pinned_buffers == 0)
 	{
-		Assert(stream->oldest_buffer_index == stream->next_buffer_index);
-
-		/* End of stream reached?  */
-		if (stream->distance == 0)
-			return InvalidBuffer;
-
-		/*
-		 * The usual order of operations is that we look ahead at the bottom
-		 * of this function after potentially finishing an I/O and making
-		 * space for more, but if we're just starting up we'll need to crank
-		 * the handle to get started.
-		 */
-		read_stream_look_ahead(stream);
-
-		/* End of stream reached? */
-		if (stream->pinned_buffers == 0)
-		{
-			Assert(stream->distance == 0);
-			return InvalidBuffer;
-		}
+		Assert(stream->distance == 0);
+		return InvalidBuffer;
 	}
 
 	/* Grab the oldest pinned buffer and associated per-buffer data. */
@@ -1022,9 +1006,6 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	/* Advance oldest buffer, with wrap-around. */
 	read_stream_advance_buffer(stream, &stream->oldest_buffer_index);
 
-	/* Prepare for the next call. */
-	read_stream_look_ahead(stream);
-
 #ifndef READ_STREAM_DISABLE_FAST_PATH
 	/* See if we can take the fast path for all-cached scans next time. */
 	if (stream->ios_in_progress == 0 &&
-- 
2.39.5

