From b38f10aa05c3ac3e9737c6c4ac7a481cece58ce8 Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Mon, 25 Aug 2025 14:33:53 +0530
Subject: [PATCH] WIP: Move PGReserveSemaphores call to
 CreateOrAttachShmemStructs

After e25626677f8076eb3ce94586136c5464ee154381, we don't need to call
PGReserveSemaphores() before InitShmemAllocation() in
CreateSharedMemoryAndSemaphores(). Instead it can be called from
CreateOrAttachShmemStructs() where all the shared memory allocations happen.

Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
---
 src/backend/port/posix_sema.c  |  6 +-----
 src/backend/port/sysv_sema.c   |  6 +-----
 src/backend/storage/ipc/ipci.c | 12 +++++++-----
 3 files changed, 9 insertions(+), 15 deletions(-)

diff --git a/src/backend/port/posix_sema.c b/src/backend/port/posix_sema.c
index 269c7460817..d7fb0c0c4da 100644
--- a/src/backend/port/posix_sema.c
+++ b/src/backend/port/posix_sema.c
@@ -215,12 +215,8 @@ PGReserveSemaphores(int maxSemas)
 		elog(PANIC, "out of memory");
 #else
 
-	/*
-	 * We must use ShmemAllocUnlocked(), since the spinlock protecting
-	 * ShmemAlloc() won't be ready yet.
-	 */
 	sharedSemas = (PGSemaphore)
-		ShmemAllocUnlocked(PGSemaphoreShmemSize(maxSemas));
+		ShmemAlloc(PGSemaphoreShmemSize(maxSemas));
 #endif
 
 	numSems = 0;
diff --git a/src/backend/port/sysv_sema.c b/src/backend/port/sysv_sema.c
index 6ac83ea1a82..9faaeeefc79 100644
--- a/src/backend/port/sysv_sema.c
+++ b/src/backend/port/sysv_sema.c
@@ -343,12 +343,8 @@ PGReserveSemaphores(int maxSemas)
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/*
-	 * We must use ShmemAllocUnlocked(), since the spinlock protecting
-	 * ShmemAlloc() won't be ready yet.
-	 */
 	sharedSemas = (PGSemaphore)
-		ShmemAllocUnlocked(PGSemaphoreShmemSize(maxSemas));
+		ShmemAlloc(PGSemaphoreShmemSize(maxSemas));
 	numSharedSemas = 0;
 	maxSharedSemas = maxSemas;
 
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 2fa045e6b0f..c4ccce45b59 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -224,11 +224,6 @@ CreateSharedMemoryAndSemaphores(void)
 
 	InitShmemAccess(seghdr);
 
-	/*
-	 * Create semaphores
-	 */
-	PGReserveSemaphores(numSemas);
-
 	/*
 	 * Set up shared memory allocation mechanism
 	 */
@@ -265,6 +260,13 @@ CreateSharedMemoryAndSemaphores(void)
 static void
 CreateOrAttachShmemStructs(void)
 {
+
+	if (!IsUnderPostmaster)
+	{
+		/* Set up semaphores */
+		PGReserveSemaphores(ProcGlobalSemas());
+	}
+
 	/*
 	 * Now initialize LWLocks, which do shared memory allocation and are
 	 * needed for InitShmemIndex.

base-commit: 878656dbde0d2fd4b85a8c63566e2a9f0d0f4952
-- 
2.34.1

