From bc2a6e9d279c38afa1ccfd60ec93ad88eaf80b36 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Sat, 5 Apr 2025 16:20:13 +0200
Subject: [PATCH v25 5/6] adjust page alignment

---
 src/backend/storage/ipc/shmem.c | 21 +++++++++++++++------
 1 file changed, 15 insertions(+), 6 deletions(-)

diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 5d979423bd9..4a9a9606f2e 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -637,13 +637,22 @@ pg_get_shmem_allocations_numa(PG_FUNCTION_ARGS)
 	while ((ent = (ShmemIndexEnt *) hash_seq_search(&hstat)) != NULL)
 	{
 		int			i;
+		char	   *startptr,
+				   *endptr;
+		Size		total_len;
 
-		/* XXX I assume we use TYPEALIGN as a way to round to whole pages.
-		 * It's a bit misleading to call that "aligned", no? */
+		/*
+		 * Calculate the range of OS pages used by this segment. The segment
+		 * may start / end half-way through a page, we want to count these
+		 * pages too. So we align the start/end pointers down/up, and then
+		 * calculate the number of pages from that.
+		 */
+		startptr = (char *) TYPEALIGN_DOWN(os_page_size, ent->location);
+		endptr = (char *) TYPEALIGN(os_page_size,
+									(char *) ent->location + ent->allocated_size);
+		total_len = (endptr - startptr);
 
-		/* Get number of OS aligned pages */
-		shm_ent_page_count
-			= TYPEALIGN(os_page_size, ent->allocated_size) / os_page_size;
+		shm_ent_page_count = total_len / os_page_size;
 
 		/*
 		 * If we get ever 0xff back from kernel inquiry, then we probably have
@@ -663,7 +672,7 @@ pg_get_shmem_allocations_numa(PG_FUNCTION_ARGS)
 		{
 			volatile uint64 touch pg_attribute_unused();
 
-			page_ptrs[i] = (char *) ent->location + (i * os_page_size);
+			page_ptrs[i] = startptr + (i * os_page_size);
 
 			if (firstNumaTouch)
 				pg_numa_touch_mem_if_required(touch, page_ptrs[i]);
-- 
2.39.5

