From a1863dacaf0a46a4fdf896c9c8e284164c0681a2 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Fri, 13 Nov 2026 18:12:06 -0500
Subject: [PATCH v6 1/2] Avoid overflow computing visibility map length

Computing the number of visibility map blocks used addition-based
ceiling division on a BlockNumber.  For heap lengths near
MaxBlockNumber, the addition could overflow and produce a much smaller
visibility map length, potentially zero.

Use quotient and remainder instead so the calculation cannot overflow.

Reported-by: Melanie Plageman <melanieplageman@gmail.com>
Author: Melanie Plageman <melanieplageman@gmail.com>
Backpatch-through: 17
---
 src/backend/access/heap/visibilitymap.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/backend/access/heap/visibilitymap.c b/src/backend/access/heap/visibilitymap.c
index fe5ce437e1b..308a6034f91 100644
--- a/src/backend/access/heap/visibilitymap.c
+++ b/src/backend/access/heap/visibilitymap.c
@@ -127,7 +127,7 @@
 /* Mapping from heap block number to the right bit in the visibility map */
 #define HEAPBLK_TO_MAPBLOCK(x) ((x) / HEAPBLOCKS_PER_PAGE)
 #define HEAPBLK_TO_MAPBLOCK_LIMIT(x) \
-	(((x) + HEAPBLOCKS_PER_PAGE - 1) / HEAPBLOCKS_PER_PAGE)
+	((x) / HEAPBLOCKS_PER_PAGE + ((x) % HEAPBLOCKS_PER_PAGE != 0))
 #define HEAPBLK_TO_MAPBYTE(x) (((x) % HEAPBLOCKS_PER_PAGE) / HEAPBLOCKS_PER_BYTE)
 #define HEAPBLK_TO_OFFSET(x) (((x) % HEAPBLOCKS_PER_BYTE) * BITS_PER_HEAPBLOCK)
 
-- 
2.43.0

