From 75bc08254e0dc3657538f2b2047689ea6242d8ba Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Tue, 1 Dec 2026 15:37:40 -0500
Subject: [PATCH v1 6/7] Lock new BRIN pages before initializing them on retry

If evacuation invalidates the source page, lock the newly extended page
before initializing it.  Leave it intact if the revmap already used it.
---
 src/backend/access/brin/brin_pageops.c | 22 ++++++++++++----------
 1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/src/backend/access/brin/brin_pageops.c b/src/backend/access/brin/brin_pageops.c
index 74014b742f6..d27b8c0cc1d 100644
--- a/src/backend/access/brin/brin_pageops.c
+++ b/src/backend/access/brin/brin_pageops.c
@@ -791,20 +791,22 @@ brin_getinsertbuffer(Relation irel, Buffer oldbuf, Size itemsz,
 				 * uninitialized page get in the FSM, so we need to initialize
 				 * it first.
 				 */
-				if (*extended)
-					brin_initialize_empty_new_buffer(irel, buf);
-
-				if (extensionLockHeld)
-					UnlockRelationForExtension(irel, ExclusiveLock);
-
-				ReleaseBuffer(buf);
-
 				if (*extended)
 				{
+					LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
+					if (extensionLockHeld)
+						UnlockRelationForExtension(irel, ExclusiveLock);
+
+					/* A revmap extension might already have claimed it. */
+					if (PageIsNew(BufferGetPage(buf)))
+						brin_initialize_empty_new_buffer(irel, buf);
+					UnlockReleaseBuffer(buf);
 					FreeSpaceMapVacuumRange(irel, newblk, newblk + 1);
 					/* shouldn't matter, but don't confuse caller */
 					*extended = false;
 				}
+				else
+					ReleaseBuffer(buf);
 
 				return InvalidBuffer;
 			}
@@ -888,8 +890,8 @@ brin_getinsertbuffer(Relation irel, Buffer oldbuf, Size itemsz,
  * Also, because we would not WAL-log the action that would initialize the
  * page, the page would go uninitialized in a standby (or after recovery).
  *
- * While we record the page in FSM here, caller is responsible for doing FSM
- * upper-page update if that seems appropriate.
+ * The caller must hold an exclusive lock on the buffer and is responsible for
+ * updating the upper FSM pages if appropriate.
  */
 static void
 brin_initialize_empty_new_buffer(Relation idxrel, Buffer buffer)
-- 
2.56.1

