From 80d441736035f26b13afc1da70d2f065c06252d7 Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Tue, 26 Aug 2025 09:47:52 +0530
Subject: [PATCH 1/2] PGReserveSemaphores() called from
 CreateSharedMemoryAndSemaphores()

Before e25626677f8076eb3ce94586136c5464ee154381, PGReserveSemaphores()
was required to be called before SpinlockSemaInit() since spinlocks may
be implemented using semaphores on some platforms.  SpinlockSemaInit()
was required to be called before InitShmemAllocation() since the latter
initialized a spinlock to synchronize shared memory allocations.
e25626677f8076eb3ce94586136c5464ee154381 removed the call to
SpinlockSemaInit() from CreateSharedMemoryAndSemaphores() but left the
call to PGReserveSemaphores() in CreateSharedMemoryAndSemaphores(), even
though it fits in CreateOrAttachShmemStructs() along with the calls to
other functions allocating shared memory structures. Add a comment
explaining this absurdity.

To be backpatched to PG 18.

Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAExHW5seSZpPx-znjidVZNzdagGHOk06F+Ds88MpPUbxd1kTaA@mail.gmail.com
---
 src/backend/storage/ipc/ipci.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 2fa045e6b0f..ff88cc06443 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -225,7 +225,12 @@ CreateSharedMemoryAndSemaphores(void)
 	InitShmemAccess(seghdr);
 
 	/*
-	 * Create semaphores
+	 * Create semaphores. This is done here because of a now-non-existent
+	 * dependency between spinlocks, which were required for shared memory
+	 * allocation, and semaphores, which were allocated in the shared memory
+	 * on some platforms. Ideally it should be done in
+	 * CreateOrAttachShmemStructs() where we allocate other shared memory
+	 * structures.
 	 */
 	PGReserveSemaphores(numSemas);
 

base-commit: 99234e9ddc02f45eb122f83d49031e2c517d0af8
-- 
2.34.1

