From 7cdcf605c4d67aa35f66e42c98a12c1b97c20b69 Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Thu, 21 Aug 2025 15:44:24 +0530
Subject: [PATCH 13/16] Update sizes and addresses of shared memory mapping and
 shared memory structures

Update totalsize and end address in segment and mapping: Once a shared
memory segment has been resized, the total size and end address of the
same needs to be updated in the corresponding AnonymousMapping and
Segment structure.

Update allocated_size for resized shared memory structure: Reallocating
the shared memory structure after resizing needs a bit more work. But at
least update the allocated_size as well along with the size of shared
memory structure.

Author: Ashutosh Bapat
---
 src/backend/port/sysv_shmem.c   | 4 ++++
 src/backend/storage/ipc/shmem.c | 6 +++++-
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index ba8613678f6..54d335b2e5d 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -1021,6 +1021,8 @@ AnonymousShmemResize(void)
 	for(int i = 0; i < ANON_MAPPINGS; i++)
 	{
 		AnonymousMapping *m = &Mappings[i];
+		ShmemSegment *segment = &Segments[i];
+		PGShmemHeader *shmem_hdr = segment->ShmemSegHdr;
 
 #ifdef MAP_HUGETLB
 		if (huge_pages_on && (m->shmem_req_size % hugepagesize != 0))
@@ -1067,6 +1069,8 @@ AnonymousShmemResize(void)
 
 		reinit = true;
 		m->shmem_size = m->shmem_req_size;
+		shmem_hdr->totalsize = m->shmem_size;
+		segment->ShmemEnd = m->shmem + m->shmem_size;
 	}
 
 	if (reinit)
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 2a197540300..0f9abf69fd5 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -504,13 +504,17 @@ ShmemInitStructInSegment(const char *name, Size size, bool *foundPtr,
 		 *
 		 * XXX: There is an implicit assumption this can only happen in
 		 * "resizable" segments, where only one shared structure is allowed.
-		 * This has to be implemented more cleanly.
+		 * This has to be implemented more cleanly. Probably we should implement
+		 * ShmemReallocRawInSegment functionality just to adjust the size
+		 * according to alignment, return the allocated size and update the
+		 * mapping offset.
 		 */
 		if (result->size != size)
 		{
 			Size delta = size - result->size;
 
 			result->size = size;
+			result->allocated_size = size;
 
 			/* Reflect size change in the shared segment */
 			SpinLockAcquire(Segments[shmem_segment].ShmemLock);
-- 
2.34.1

