Fix some rounding code for shared memory.
authorNathan Bossart <nathan@postgresql.org>
Fri, 23 Jan 2026 16:46:49 +0000 (10:46 -0600)
committerNathan Bossart <nathan@postgresql.org>
Fri, 23 Jan 2026 16:46:49 +0000 (10:46 -0600)
InitializeShmemGUCs() always added 1 to the value calculated for
shared_memory_size_in_huge_pages, which is unnecessary if the
shared memory size is divisible by the huge page size.

CreateAnonymousSegment() neglected to check for overflow when
rounding up to a multiple of the huge page size.

These are arguably bugs, but they seem extremely unlikely to be
causing problems in practice, so no back-patch.

Author: Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/CAO6_Xqq2vZbva0R9eQSY0p2kfksX2aP4r%3D%2BZ_q1HBYNU%3Dm8bBg%40mail.gmail.com

src/backend/port/sysv_shmem.c
src/backend/storage/ipc/ipci.c

index de49189711808f2769caa50c14f0b9a37ac6df16..53f7a64fa45ac22844a915d30e732587defedd25 100644 (file)
@@ -617,7 +617,7 @@ CreateAnonymousSegment(Size *size)
        GetHugePageSize(&hugepagesize, &mmap_flags);
 
        if (allocsize % hugepagesize != 0)
-           allocsize += hugepagesize - (allocsize % hugepagesize);
+           allocsize = add_size(allocsize, hugepagesize - (allocsize % hugepagesize));
 
        ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
                   PG_MMAP_FLAGS | mmap_flags, -1, 0);
index 85c67b2c183d649a97352183269967fac350ce16..2a3dfedf7e9f30672d11aeb45934dc105e5ab2e3 100644 (file)
@@ -363,7 +363,9 @@ InitializeShmemGUCs(void)
    {
        Size        hp_required;
 
-       hp_required = add_size(size_b / hp_size, 1);
+       hp_required = size_b / hp_size;
+       if (size_b % hp_size != 0)
+           hp_required = add_size(hp_required, 1);
        sprintf(buf, "%zu", hp_required);
        SetConfigOption("shared_memory_size_in_huge_pages", buf,
                        PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);