From c3c030c3fb3a2c39a164a7ab1b7bea9df5f5a9b7 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Sat, 5 Apr 2025 16:00:39 +0200
Subject: [PATCH v25 3/6] adjust page_num

---
 contrib/pg_buffercache/pg_buffercache_pages.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/contrib/pg_buffercache/pg_buffercache_pages.c b/contrib/pg_buffercache/pg_buffercache_pages.c
index 0b96476c319..a3c4a2578d9 100644
--- a/contrib/pg_buffercache/pg_buffercache_pages.c
+++ b/contrib/pg_buffercache/pg_buffercache_pages.c
@@ -315,6 +315,7 @@ pg_buffercache_numa_pages(PG_FUNCTION_ARGS)
 		int			pages_per_buffer;
 		int			buffers_per_page;
 		volatile uint64 touch pg_attribute_unused();
+		char	   *startptr = NULL;
 
 		if (pg_numa_init() == -1)
 			elog(ERROR, "libnuma initialization failed or NUMA is not supported on this platform");
@@ -437,6 +438,7 @@ pg_buffercache_numa_pages(PG_FUNCTION_ARGS)
 		 * to one big big move_pages(2) inquiry system call. Basically we ask
 		 * for all memory pages for NBuffers.
 		 */
+		startptr = (char *) BufferGetBlock(1);
 		idx = 0;
 		for (i = 0; i < NBuffers; i++)
 		{
@@ -469,11 +471,14 @@ pg_buffercache_numa_pages(PG_FUNCTION_ARGS)
 				char	   *buffptr = (char *) BufferGetBlock(i + 1);
 
 				fctx->record[idx].bufferid = bufferid;
-				fctx->record[idx].numa_page = j;
 
 				os_page_ptrs[idx]
-					= (char *) TYPEALIGN(os_page_size,
-										 buffptr + (os_page_size * j));
+					= (char *) TYPEALIGN_DOWN(os_page_size,
+											  buffptr + (os_page_size * j));
+
+				/* calculate ID of the OS memory page */
+				fctx->record[idx].numa_page
+					= ((char *) os_page_ptrs[idx] - startptr) / os_page_size;
 
 				/* Only need to touch memory once per backend process lifetime */
 				if (firstNumaTouch)
-- 
2.39.5

