agora inbox for pgsql-hackers@postgresql.org  
help / color / mirror / Atom feed
[PATCH v4 2/8] Address space reservation for shared memory
213+ messages / 2 participants
[nested] [flat]

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v4 2/8] Address space reservation for shared memory
@ 2024-10-16 18:21  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2024-10-16 18:21 UTC (permalink / raw)

Currently the kernel is responsible to chose an address, where to place each
shared memory mapping, which is the lowest possible address that do not clash
with any other mappings. This is considered to be the most portable approach,
but one of the downsides is that there is no place to resize allocated mappings
anymore. Here is how it looks like for one mapping in /proc/$PID/maps,
/dev/zero represents the anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
    ...
    7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
    7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)

By specifying the mapping address directly it's possible to place the
mapping in a way that leaves room for resizing. The idea is:

* To reserve some address space via mmap'ing a large chunk of memory
  with PROT_NONE and MAP_NORESERVE. This way we prepare a playground for
  preparing shared memory layout without risking anything interfering
  with that.

* To slice the reserved space up into sections, one to use for each
  shared segment.

* Allocate shared memory segments out of corresponding slices and
  leaving unclaimed space in between them. This is implemented via
  mmap'ing memory at a specified address from the reserved space with
  MAP_FIXED.

The result looks like this:

    012d9000-0133e000         [heap]
    7f443a800000-7f444196c000 /dev/zero (deleted)
    7f444196c000-7f470a800000                     # reserved space
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2

Things like address space randomization should not be a problem in this
context, since the randomization is applied to the mmap base, which is
one per process.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21250648 kB
    VmRSS:             22948 kB
    RssAnon:             768 kB
    RssFile:           10404 kB
    RssShmem:          11776 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    17637376 (~16.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.
---
 src/backend/port/sysv_shmem.c       | 284 ++++++++++++++++++++++++----
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/storage/pg_shmem.h      |   4 +-
 6 files changed, 271 insertions(+), 39 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..a0f03ff868f 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -108,6 +108,66 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping placing (/dev/zero (deleted) below) looks like this:
+ *
+ * 00400000-00490000         /path/bin/postgres
+ * ...
+ * 012d9000-0133e000         [heap]
+ * 7f443a800000-7f470a800000 /dev/zero (deleted)
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * ...
+ * 7f471aef2000-7f471aef9000 /dev/shm/PostgreSQL.3859891842
+ * 7f471aef9000-7f471aefa000 /SYSV007dbf7d (deleted)
+ * ...
+ *
+ * We would like to place multiple mappings in such a way, that there will be
+ * enough space between them in the address space to be able to resize up to
+ * certain size, but without counting towards the total memory consumption.
+ *
+ * To achieve that we first reserve some shared memory address space by
+ * mmap'ing a segment of MaxAvailableMemory size with PROT_NONE and
+ * MAP_NORESERVE (these flags allow to make sure this space will not be used by
+ * anything else, yet do not count against memory limits). Having the reserved
+ * space, we allocate out of it actual chunks of shared memory as usual,
+ * updating a pointer to the current available reserved space for the next
+ * allocation with the gap between segments in mind.
+ *
+ * The result would look like this:
+ *
+ * 012d9000-0133e000         [heap]
+ * 7f4426f54000-7f442e010000 /dev/zero (deleted)
+ * 7f442e010000-7f443a800000                     # reserved empty space
+ * 7f443a800000-7f444196c000 /dev/zero (deleted)
+ * 7f444196c000-7f470a800000                     # reserved empty space
+ * 7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
+ * 7f4718400000-7f4718401000 /usr/lib64/libicudata.so.74.2
+ * [...]
+ *
+ * The reserved space pointer is calculated to slice up the total reserved
+ * space into fixed fractions of address space for each segment, as specified
+ * in the SHMEM_RESIZE_RATIO array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Offset from the beginning of the reserved space, which indicates currently
+ * available range. New shared memory segments have to be allocated at this
+ * offset related to the reserved space.
+ */
+static Size reserved_offset = 0;
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -626,39 +686,198 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  *
  * This function will modify mapping size to the actual size of the allocation,
  * if it ends up allocating a segment that is larger than requested.
+ *
+ * Note that we do not switch from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
-CreateAnonymousSegment(AnonymousMapping *mapping)
+CreateAnonymousSegment(AnonymousMapping *mapping, Pointer base)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS;
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* ReserveAnonymousMemory should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
+	}
+#endif
+
+	elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p",
+		 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
+	/*
+	 * Try to create mapping at an address out of the reserved range, which
+	 * will allow to extend it later. Use reserved_offset to allocate the
+	 * segment, then update currently available reserved range.
+	 *
+	 * If the last step has failed, fallback to the regular mapping
+	 * creation and signal that shared buffers could not be resized without
+	 * a restart.
+	 */
+	ptr = mmap(base + reserved_offset, allocsize, PROT_READ | PROT_WRITE,
+			   mmap_flags | MAP_FIXED, -1, 0);
+	mmap_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+		elog(DEBUG1, "segment[%s]: mmap(%zu) at address %p failed: %m, "
+					 "fallback to the non-resizable allocation",
+			 MappingName(mapping->shmem_segment), allocsize, base + reserved_offset);
+
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
+						   PG_MMAP_FLAGS, -1, 0);
+		mmap_errno = errno;
+	}
+	else
+	{
+		Size total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+
+		reserved_offset += total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+	}
+
+	if (ptr == MAP_FAILED)
+	{
+		errno = mmap_errno;
+		DebugMappings();
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment)),
+				 (mmap_errno == ENOMEM) ?
+				 errhint("This error usually means that PostgreSQL's request "
+						 "for a shared memory segment exceeded available memory, "
+						 "swap space, or huge pages. To reduce the request size "
+						 "(currently %zu bytes), reduce PostgreSQL's shared "
+						 "memory usage, perhaps by reducing \"shared_buffers\" or "
+						 "\"max_connections\".",
+						 allocsize) : 0));
+	}
+
+	mapping->shmem = ptr;
+	mapping->shmem_size = allocsize;
+}
+
+/*
+ * ReserveAnonymousMemory
+ *
+ * Reserve shared memory address space, from which shared memory segments are
+ * going to be sliced out. The goal of this exercise is to support segments
+ * resizing, for which we need a reserved space free of potential clashes with
+ * other mmap'd areas that are not under our control. Reservation is done via
+ * mmap, and will not allocate any memory until it will be actually used, and
+ * MAP_NORESERVE allows to make it not counting againt kernel reservation
+ * limits (e.g. in cgroups or for huge pages). Do not get confused because of
+ * MAP_NORESERVE -- we need to reserve some space, but not the actual memory,
+ * and that is that this flag is about.
+ *
+ * Note, that with MAP_NORESERVE a reservation with hugetlb will succeed even
+ * if there is actually not enough huge pages. Hence this function is
+ * responsible for deciding whether to use huge pages or not. To achieve that
+ * we need to probe first and try to allocate needed memory for all segments --
+ * if this succeeds, we unmap the probe segment and use hugetlb; if it fails,
+ * we proceed with the regular memory.
+ */
+void *
+ReserveAnonymousMemory(Size reserve_size)
+{
+	Size		allocsize = reserve_size;
+	void	   *ptr = MAP_FAILED;
+	int			mmap_errno = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 *
+		 * We could actually have a mix and match of segments with and without
+		 * huge pages. But in that case we need to have multiple reservation
+		 * spaces to use corresponding memory (hugetlb adress space reserved
+		 * for hugetlb segments, regular memory for others), and it doesn't
+		 * seem to worth the complexity for now.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
 		mmap_errno = errno;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
 		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
+			/* No huge pages, we will go with the regular page size */
+			elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB "
+						 "failed, huge pages disabled: %m", total_size);
+		}
+		else
+		{
+			/*
+			 * All fine, unmap the temporary segment and proceed with reserving
+			 * using huge pages.
+			 */
+			if (munmap(ptr, total_size) < 0)
+				elog(LOG, "reservice space: munmap(%p, %zu) failed: %m",
+					 ptr, total_size);
+
+			/* Round up the requested size to a suitable large value. */
+			if (allocsize % hugepagesize != 0)
+				allocsize += hugepagesize - (allocsize % hugepagesize);
+
+			elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB",
+						 allocsize);
+			ptr = mmap(NULL, allocsize, PROT_NONE,
+					   PG_MMAP_FLAGS | MAP_ANONYMOUS | MAP_NORESERVE | mmap_flags,
+					   -1, 0);
+			mmap_errno = errno;
+
+			/* This should not happen, but handle errors anyway */
+			if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
+			{
+				elog(DEBUG1, "reserving space: mmap(%zu) with MAP_HUGETLB "
+							 "failed, huge pages disabled: %m", allocsize);
+			}
 		}
 	}
 #endif
@@ -666,10 +885,12 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 	/*
 	 * Report whether huge pages are in use.  This needs to be tracked before
 	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * previously. At this point ptr is either pointing to the probe segment,
+	 * if we couldn't mmap it, or the reservation space.
 	 */
 	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
@@ -677,10 +898,11 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		 * Use the original size, not the rounded-up value, when falling back
 		 * to non-huge pages.
 		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
+		allocsize = reserve_size;
+
+		elog(DEBUG1, "reserving space: mmap(%zu)", allocsize);
+		ptr = mmap(NULL, allocsize, PROT_NONE,
+				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
 	}
 
 	if (ptr == MAP_FAILED)
@@ -688,20 +910,18 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 		errno = mmap_errno;
 		DebugMappings();
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
-						MappingName(mapping->shmem_segment)),
+				(errmsg("reserving space: could not map anonymous shared "
+						"memory: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
-						 "for a shared memory segment exceeded available memory, "
-						 "swap space, or huge pages. To reduce the request size "
-						 "(currently %zu bytes), reduce PostgreSQL's shared "
-						 "memory usage, perhaps by reducing \"shared_buffers\" or "
-						 "\"max_connections\".",
+						 "for a reserved shared memory address space exceeded "
+						 "available memory, swap space, or huge pages. To "
+						 "reduce the request reservation size (currently %zu "
+						 "bytes), reduce PostgreSQL's \"maximum_shared_buffers\".",
 						 allocsize) : 0));
 	}
 
-	mapping->shmem = ptr;
-	mapping->shmem_size = allocsize;
+	return ptr;
 }
 
 /*
@@ -740,7 +960,7 @@ AnonymousShmemDetach(int status, Datum arg)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -760,14 +980,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -782,7 +994,7 @@ PGSharedMemoryCreate(Size size,
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
 		/* On success, mapping data will be modified. */
-		CreateAnonymousSegment(mapping);
+		CreateAnonymousSegment(mapping, base);
 
 		next_free_segment++;
 
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..ce719f1b412 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -205,7 +205,7 @@ EnableLockPagesPrivilege(int elevel)
  */
 PGShmemHeader *
 PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+					 PGShmemHeader **shim, Pointer base)
 {
 	void	   *memAddress;
 	PGShmemHeader *hdr;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..076888c0172 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -203,9 +203,12 @@ CreateSharedMemoryAndSemaphores(void)
 	PGShmemHeader *seghdr;
 	Size		size;
 	int			numSemas;
+	void 		*base;
 
 	Assert(!IsUnderPostmaster);
 
+	base = ReserveAnonymousMemory((Size) MaxAvailableMemory * BLCKSZ);
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -217,7 +220,7 @@ CreateSharedMemoryAndSemaphores(void)
 		 *
 		 * XXX: Do multiple shims are needed, one per segment?
 		 */
-		seghdr = PGSharedMemoryCreate(size, &shim);
+		seghdr = PGSharedMemoryCreate(size, &shim, base);
 
 		/*
 		 * Make sure that huge pages are never reported as "unknown" while the
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 2152aad97d9..1d42a5856c0 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 131072;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index 4eaeca89f2c..dede37f7905 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2364,6 +2364,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		131072, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 138078c29c5..4a83e255652 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -60,6 +60,7 @@ extern PGDLLIMPORT ShmemSegment Segments[ANON_MAPPINGS];
 extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -100,10 +101,11 @@ extern void PGSharedMemoryNoReAttach(void);
 #endif
 
 extern PGShmemHeader *PGSharedMemoryCreate(Size size,
-										   PGShmemHeader **shim);
+										   PGShmemHeader **shim, Pointer base);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+void *ReserveAnonymousMemory(Size reserve_size);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.45.1


--vninua6xybvzgrci
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v4-0003-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v24 7/8] Row pattern recognition patch (tests).
@ 2024-12-19 06:06  Tatsuo Ishii <ishii@postgresql.org>
  0 siblings, 0 replies; 213+ messages in thread

From: Tatsuo Ishii @ 2024-12-19 06:06 UTC (permalink / raw)

---
 src/test/regress/expected/rpr.out  | 919 +++++++++++++++++++++++++++++
 src/test/regress/parallel_schedule |   2 +-
 src/test/regress/sql/rpr.sql       | 467 +++++++++++++++
 3 files changed, 1387 insertions(+), 1 deletion(-)
 create mode 100644 src/test/regress/expected/rpr.out
 create mode 100644 src/test/regress/sql/rpr.sql

diff --git a/src/test/regress/expected/rpr.out b/src/test/regress/expected/rpr.out
new file mode 100644
index 0000000000..b8cd6190b4
--- /dev/null
+++ b/src/test/regress/expected/rpr.out
@@ -0,0 +1,919 @@
+--
+-- Test for row pattern definition clause
+--
+CREATE TEMP TABLE stock (
+       company TEXT,
+       tdate DATE,
+       price INTEGER
+);
+INSERT INTO stock VALUES ('company1', '2023-07-01', 100);
+INSERT INTO stock VALUES ('company1', '2023-07-02', 200);
+INSERT INTO stock VALUES ('company1', '2023-07-03', 150);
+INSERT INTO stock VALUES ('company1', '2023-07-04', 140);
+INSERT INTO stock VALUES ('company1', '2023-07-05', 150);
+INSERT INTO stock VALUES ('company1', '2023-07-06', 90);
+INSERT INTO stock VALUES ('company1', '2023-07-07', 110);
+INSERT INTO stock VALUES ('company1', '2023-07-08', 130);
+INSERT INTO stock VALUES ('company1', '2023-07-09', 120);
+INSERT INTO stock VALUES ('company1', '2023-07-10', 130);
+INSERT INTO stock VALUES ('company2', '2023-07-01', 50);
+INSERT INTO stock VALUES ('company2', '2023-07-02', 2000);
+INSERT INTO stock VALUES ('company2', '2023-07-03', 1500);
+INSERT INTO stock VALUES ('company2', '2023-07-04', 1400);
+INSERT INTO stock VALUES ('company2', '2023-07-05', 1500);
+INSERT INTO stock VALUES ('company2', '2023-07-06', 60);
+INSERT INTO stock VALUES ('company2', '2023-07-07', 1100);
+INSERT INTO stock VALUES ('company2', '2023-07-08', 1300);
+INSERT INTO stock VALUES ('company2', '2023-07-09', 1200);
+INSERT INTO stock VALUES ('company2', '2023-07-10', 1300);
+SELECT * FROM stock;
+ company  |   tdate    | price 
+----------+------------+-------
+ company1 | 07-01-2023 |   100
+ company1 | 07-02-2023 |   200
+ company1 | 07-03-2023 |   150
+ company1 | 07-04-2023 |   140
+ company1 | 07-05-2023 |   150
+ company1 | 07-06-2023 |    90
+ company1 | 07-07-2023 |   110
+ company1 | 07-08-2023 |   130
+ company1 | 07-09-2023 |   120
+ company1 | 07-10-2023 |   130
+ company2 | 07-01-2023 |    50
+ company2 | 07-02-2023 |  2000
+ company2 | 07-03-2023 |  1500
+ company2 | 07-04-2023 |  1400
+ company2 | 07-05-2023 |  1500
+ company2 | 07-06-2023 |    60
+ company2 | 07-07-2023 |  1100
+ company2 | 07-08-2023 |  1300
+ company2 | 07-09-2023 |  1200
+ company2 | 07-10-2023 |  1300
+(20 rows)
+
+-- basic test using PREV
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
+ nth_value(tdate, 2) OVER w AS nth_second
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | first_value | last_value | nth_second 
+----------+------------+-------+-------------+------------+------------
+ company1 | 07-01-2023 |   100 |         100 |        140 | 07-02-2023
+ company1 | 07-02-2023 |   200 |             |            | 
+ company1 | 07-03-2023 |   150 |             |            | 
+ company1 | 07-04-2023 |   140 |             |            | 
+ company1 | 07-05-2023 |   150 |             |            | 
+ company1 | 07-06-2023 |    90 |          90 |        120 | 07-07-2023
+ company1 | 07-07-2023 |   110 |             |            | 
+ company1 | 07-08-2023 |   130 |             |            | 
+ company1 | 07-09-2023 |   120 |             |            | 
+ company1 | 07-10-2023 |   130 |             |            | 
+ company2 | 07-01-2023 |    50 |          50 |       1400 | 07-02-2023
+ company2 | 07-02-2023 |  2000 |             |            | 
+ company2 | 07-03-2023 |  1500 |             |            | 
+ company2 | 07-04-2023 |  1400 |             |            | 
+ company2 | 07-05-2023 |  1500 |             |            | 
+ company2 | 07-06-2023 |    60 |          60 |       1200 | 07-07-2023
+ company2 | 07-07-2023 |  1100 |             |            | 
+ company2 | 07-08-2023 |  1300 |             |            | 
+ company2 | 07-09-2023 |  1200 |             |            | 
+ company2 | 07-10-2023 |  1300 |             |            | 
+(20 rows)
+
+-- basic test using PREV. UP appears twice
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
+ nth_value(tdate, 2) OVER w AS nth_second
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+ UP+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | first_value | last_value | nth_second 
+----------+------------+-------+-------------+------------+------------
+ company1 | 07-01-2023 |   100 |         100 |        150 | 07-02-2023
+ company1 | 07-02-2023 |   200 |             |            | 
+ company1 | 07-03-2023 |   150 |             |            | 
+ company1 | 07-04-2023 |   140 |             |            | 
+ company1 | 07-05-2023 |   150 |             |            | 
+ company1 | 07-06-2023 |    90 |          90 |        130 | 07-07-2023
+ company1 | 07-07-2023 |   110 |             |            | 
+ company1 | 07-08-2023 |   130 |             |            | 
+ company1 | 07-09-2023 |   120 |             |            | 
+ company1 | 07-10-2023 |   130 |             |            | 
+ company2 | 07-01-2023 |    50 |          50 |       1500 | 07-02-2023
+ company2 | 07-02-2023 |  2000 |             |            | 
+ company2 | 07-03-2023 |  1500 |             |            | 
+ company2 | 07-04-2023 |  1400 |             |            | 
+ company2 | 07-05-2023 |  1500 |             |            | 
+ company2 | 07-06-2023 |    60 |          60 |       1300 | 07-07-2023
+ company2 | 07-07-2023 |  1100 |             |            | 
+ company2 | 07-08-2023 |  1300 |             |            | 
+ company2 | 07-09-2023 |  1200 |             |            | 
+ company2 | 07-10-2023 |  1300 |             |            | 
+(20 rows)
+
+-- basic test using PREV. Use '*'
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
+ nth_value(tdate, 2) OVER w AS nth_second
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP* DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | first_value | last_value | nth_second 
+----------+------------+-------+-------------+------------+------------
+ company1 | 07-01-2023 |   100 |         100 |        140 | 07-02-2023
+ company1 | 07-02-2023 |   200 |             |            | 
+ company1 | 07-03-2023 |   150 |             |            | 
+ company1 | 07-04-2023 |   140 |             |            | 
+ company1 | 07-05-2023 |   150 |         150 |         90 | 07-06-2023
+ company1 | 07-06-2023 |    90 |             |            | 
+ company1 | 07-07-2023 |   110 |         110 |        120 | 07-08-2023
+ company1 | 07-08-2023 |   130 |             |            | 
+ company1 | 07-09-2023 |   120 |             |            | 
+ company1 | 07-10-2023 |   130 |             |            | 
+ company2 | 07-01-2023 |    50 |          50 |       1400 | 07-02-2023
+ company2 | 07-02-2023 |  2000 |             |            | 
+ company2 | 07-03-2023 |  1500 |             |            | 
+ company2 | 07-04-2023 |  1400 |             |            | 
+ company2 | 07-05-2023 |  1500 |        1500 |         60 | 07-06-2023
+ company2 | 07-06-2023 |    60 |             |            | 
+ company2 | 07-07-2023 |  1100 |        1100 |       1200 | 07-08-2023
+ company2 | 07-08-2023 |  1300 |             |            | 
+ company2 | 07-09-2023 |  1200 |             |            | 
+ company2 | 07-10-2023 |  1300 |             |            | 
+(20 rows)
+
+-- basic test with none greedy pattern
+SELECT company, tdate, price, count(*) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (A A A)
+ DEFINE
+  A AS price >= 140 AND price <= 150
+);
+ company  |   tdate    | price | count 
+----------+------------+-------+-------
+ company1 | 07-01-2023 |   100 |     0
+ company1 | 07-02-2023 |   200 |     0
+ company1 | 07-03-2023 |   150 |     3
+ company1 | 07-04-2023 |   140 |     0
+ company1 | 07-05-2023 |   150 |     0
+ company1 | 07-06-2023 |    90 |     0
+ company1 | 07-07-2023 |   110 |     0
+ company1 | 07-08-2023 |   130 |     0
+ company1 | 07-09-2023 |   120 |     0
+ company1 | 07-10-2023 |   130 |     0
+ company2 | 07-01-2023 |    50 |     0
+ company2 | 07-02-2023 |  2000 |     0
+ company2 | 07-03-2023 |  1500 |     0
+ company2 | 07-04-2023 |  1400 |     0
+ company2 | 07-05-2023 |  1500 |     0
+ company2 | 07-06-2023 |    60 |     0
+ company2 | 07-07-2023 |  1100 |     0
+ company2 | 07-08-2023 |  1300 |     0
+ company2 | 07-09-2023 |  1200 |     0
+ company2 | 07-10-2023 |  1300 |     0
+(20 rows)
+
+-- last_value() should remain consistent
+SELECT company, tdate, price, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | last_value 
+----------+------------+-------+------------
+ company1 | 07-01-2023 |   100 |        140
+ company1 | 07-02-2023 |   200 |           
+ company1 | 07-03-2023 |   150 |           
+ company1 | 07-04-2023 |   140 |           
+ company1 | 07-05-2023 |   150 |           
+ company1 | 07-06-2023 |    90 |        120
+ company1 | 07-07-2023 |   110 |           
+ company1 | 07-08-2023 |   130 |           
+ company1 | 07-09-2023 |   120 |           
+ company1 | 07-10-2023 |   130 |           
+ company2 | 07-01-2023 |    50 |       1400
+ company2 | 07-02-2023 |  2000 |           
+ company2 | 07-03-2023 |  1500 |           
+ company2 | 07-04-2023 |  1400 |           
+ company2 | 07-05-2023 |  1500 |           
+ company2 | 07-06-2023 |    60 |       1200
+ company2 | 07-07-2023 |  1100 |           
+ company2 | 07-08-2023 |  1300 |           
+ company2 | 07-09-2023 |  1200 |           
+ company2 | 07-10-2023 |  1300 |           
+(20 rows)
+
+-- omit "START" in DEFINE but it is ok because "START AS TRUE" is
+-- implicitly defined. per spec.
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
+ nth_value(tdate, 2) OVER w AS nth_second
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | first_value | last_value | nth_second 
+----------+------------+-------+-------------+------------+------------
+ company1 | 07-01-2023 |   100 |         100 |        140 | 07-02-2023
+ company1 | 07-02-2023 |   200 |             |            | 
+ company1 | 07-03-2023 |   150 |             |            | 
+ company1 | 07-04-2023 |   140 |             |            | 
+ company1 | 07-05-2023 |   150 |             |            | 
+ company1 | 07-06-2023 |    90 |          90 |        120 | 07-07-2023
+ company1 | 07-07-2023 |   110 |             |            | 
+ company1 | 07-08-2023 |   130 |             |            | 
+ company1 | 07-09-2023 |   120 |             |            | 
+ company1 | 07-10-2023 |   130 |             |            | 
+ company2 | 07-01-2023 |    50 |          50 |       1400 | 07-02-2023
+ company2 | 07-02-2023 |  2000 |             |            | 
+ company2 | 07-03-2023 |  1500 |             |            | 
+ company2 | 07-04-2023 |  1400 |             |            | 
+ company2 | 07-05-2023 |  1500 |             |            | 
+ company2 | 07-06-2023 |    60 |          60 |       1200 | 07-07-2023
+ company2 | 07-07-2023 |  1100 |             |            | 
+ company2 | 07-08-2023 |  1300 |             |            | 
+ company2 | 07-09-2023 |  1200 |             |            | 
+ company2 | 07-10-2023 |  1300 |             |            | 
+(20 rows)
+
+-- the first row start with less than or equal to 100
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (LOWPRICE UP+ DOWN+)
+ DEFINE
+  LOWPRICE AS price <= 100,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | first_value | last_value 
+----------+------------+-------+-------------+------------
+ company1 | 07-01-2023 |   100 |         100 |        140
+ company1 | 07-02-2023 |   200 |             |           
+ company1 | 07-03-2023 |   150 |             |           
+ company1 | 07-04-2023 |   140 |             |           
+ company1 | 07-05-2023 |   150 |             |           
+ company1 | 07-06-2023 |    90 |          90 |        120
+ company1 | 07-07-2023 |   110 |             |           
+ company1 | 07-08-2023 |   130 |             |           
+ company1 | 07-09-2023 |   120 |             |           
+ company1 | 07-10-2023 |   130 |             |           
+ company2 | 07-01-2023 |    50 |          50 |       1400
+ company2 | 07-02-2023 |  2000 |             |           
+ company2 | 07-03-2023 |  1500 |             |           
+ company2 | 07-04-2023 |  1400 |             |           
+ company2 | 07-05-2023 |  1500 |             |           
+ company2 | 07-06-2023 |    60 |          60 |       1200
+ company2 | 07-07-2023 |  1100 |             |           
+ company2 | 07-08-2023 |  1300 |             |           
+ company2 | 07-09-2023 |  1200 |             |           
+ company2 | 07-10-2023 |  1300 |             |           
+(20 rows)
+
+-- second row raises 120%
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (LOWPRICE UP+ DOWN+)
+ DEFINE
+  LOWPRICE AS price <= 100,
+  UP AS price > PREV(price) * 1.2,
+  DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | first_value | last_value 
+----------+------------+-------+-------------+------------
+ company1 | 07-01-2023 |   100 |         100 |        140
+ company1 | 07-02-2023 |   200 |             |           
+ company1 | 07-03-2023 |   150 |             |           
+ company1 | 07-04-2023 |   140 |             |           
+ company1 | 07-05-2023 |   150 |             |           
+ company1 | 07-06-2023 |    90 |             |           
+ company1 | 07-07-2023 |   110 |             |           
+ company1 | 07-08-2023 |   130 |             |           
+ company1 | 07-09-2023 |   120 |             |           
+ company1 | 07-10-2023 |   130 |             |           
+ company2 | 07-01-2023 |    50 |          50 |       1400
+ company2 | 07-02-2023 |  2000 |             |           
+ company2 | 07-03-2023 |  1500 |             |           
+ company2 | 07-04-2023 |  1400 |             |           
+ company2 | 07-05-2023 |  1500 |             |           
+ company2 | 07-06-2023 |    60 |             |           
+ company2 | 07-07-2023 |  1100 |             |           
+ company2 | 07-08-2023 |  1300 |             |           
+ company2 | 07-09-2023 |  1200 |             |           
+ company2 | 07-10-2023 |  1300 |             |           
+(20 rows)
+
+-- using NEXT
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UPDOWN)
+ DEFINE
+  START AS TRUE,
+  UPDOWN AS price > PREV(price) AND price > NEXT(price)
+);
+ company  |   tdate    | price | first_value | last_value 
+----------+------------+-------+-------------+------------
+ company1 | 07-01-2023 |   100 |         100 |        200
+ company1 | 07-02-2023 |   200 |             |           
+ company1 | 07-03-2023 |   150 |             |           
+ company1 | 07-04-2023 |   140 |         140 |        150
+ company1 | 07-05-2023 |   150 |             |           
+ company1 | 07-06-2023 |    90 |             |           
+ company1 | 07-07-2023 |   110 |         110 |        130
+ company1 | 07-08-2023 |   130 |             |           
+ company1 | 07-09-2023 |   120 |             |           
+ company1 | 07-10-2023 |   130 |             |           
+ company2 | 07-01-2023 |    50 |          50 |       2000
+ company2 | 07-02-2023 |  2000 |             |           
+ company2 | 07-03-2023 |  1500 |             |           
+ company2 | 07-04-2023 |  1400 |        1400 |       1500
+ company2 | 07-05-2023 |  1500 |             |           
+ company2 | 07-06-2023 |    60 |             |           
+ company2 | 07-07-2023 |  1100 |        1100 |       1300
+ company2 | 07-08-2023 |  1300 |             |           
+ company2 | 07-09-2023 |  1200 |             |           
+ company2 | 07-10-2023 |  1300 |             |           
+(20 rows)
+
+-- using AFTER MATCH SKIP TO NEXT ROW
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ INITIAL
+ PATTERN (START UPDOWN)
+ DEFINE
+  START AS TRUE,
+  UPDOWN AS price > PREV(price) AND price > NEXT(price)
+);
+ company  |   tdate    | price | first_value | last_value 
+----------+------------+-------+-------------+------------
+ company1 | 07-01-2023 |   100 |         100 |        200
+ company1 | 07-02-2023 |   200 |             |           
+ company1 | 07-03-2023 |   150 |             |           
+ company1 | 07-04-2023 |   140 |         140 |        150
+ company1 | 07-05-2023 |   150 |             |           
+ company1 | 07-06-2023 |    90 |             |           
+ company1 | 07-07-2023 |   110 |         110 |        130
+ company1 | 07-08-2023 |   130 |             |           
+ company1 | 07-09-2023 |   120 |             |           
+ company1 | 07-10-2023 |   130 |             |           
+ company2 | 07-01-2023 |    50 |          50 |       2000
+ company2 | 07-02-2023 |  2000 |             |           
+ company2 | 07-03-2023 |  1500 |             |           
+ company2 | 07-04-2023 |  1400 |        1400 |       1500
+ company2 | 07-05-2023 |  1500 |             |           
+ company2 | 07-06-2023 |    60 |             |           
+ company2 | 07-07-2023 |  1100 |        1100 |       1300
+ company2 | 07-08-2023 |  1300 |             |           
+ company2 | 07-09-2023 |  1200 |             |           
+ company2 | 07-10-2023 |  1300 |             |           
+(20 rows)
+
+-- match everything
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP PAST LAST ROW
+ INITIAL
+ PATTERN (A+)
+ DEFINE
+  A AS TRUE
+);
+ company  |   tdate    | price | first_value | last_value 
+----------+------------+-------+-------------+------------
+ company1 | 07-01-2023 |   100 |         100 |        130
+ company1 | 07-02-2023 |   200 |             |           
+ company1 | 07-03-2023 |   150 |             |           
+ company1 | 07-04-2023 |   140 |             |           
+ company1 | 07-05-2023 |   150 |             |           
+ company1 | 07-06-2023 |    90 |             |           
+ company1 | 07-07-2023 |   110 |             |           
+ company1 | 07-08-2023 |   130 |             |           
+ company1 | 07-09-2023 |   120 |             |           
+ company1 | 07-10-2023 |   130 |             |           
+ company2 | 07-01-2023 |    50 |          50 |       1300
+ company2 | 07-02-2023 |  2000 |             |           
+ company2 | 07-03-2023 |  1500 |             |           
+ company2 | 07-04-2023 |  1400 |             |           
+ company2 | 07-05-2023 |  1500 |             |           
+ company2 | 07-06-2023 |    60 |             |           
+ company2 | 07-07-2023 |  1100 |             |           
+ company2 | 07-08-2023 |  1300 |             |           
+ company2 | 07-09-2023 |  1200 |             |           
+ company2 | 07-10-2023 |  1300 |             |           
+(20 rows)
+
+-- backtracking with reclassification of rows
+-- using AFTER MATCH SKIP PAST LAST ROW
+SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP PAST LAST ROW
+ INITIAL
+ PATTERN (A+ B+)
+ DEFINE
+  A AS price > 100,
+  B AS price > 100
+);
+ company  |   tdate    | price | first_value | last_value 
+----------+------------+-------+-------------+------------
+ company1 | 07-01-2023 |   100 |             | 
+ company1 | 07-02-2023 |   200 | 07-02-2023  | 07-05-2023
+ company1 | 07-03-2023 |   150 |             | 
+ company1 | 07-04-2023 |   140 |             | 
+ company1 | 07-05-2023 |   150 |             | 
+ company1 | 07-06-2023 |    90 |             | 
+ company1 | 07-07-2023 |   110 | 07-07-2023  | 07-10-2023
+ company1 | 07-08-2023 |   130 |             | 
+ company1 | 07-09-2023 |   120 |             | 
+ company1 | 07-10-2023 |   130 |             | 
+ company2 | 07-01-2023 |    50 |             | 
+ company2 | 07-02-2023 |  2000 | 07-02-2023  | 07-05-2023
+ company2 | 07-03-2023 |  1500 |             | 
+ company2 | 07-04-2023 |  1400 |             | 
+ company2 | 07-05-2023 |  1500 |             | 
+ company2 | 07-06-2023 |    60 |             | 
+ company2 | 07-07-2023 |  1100 | 07-07-2023  | 07-10-2023
+ company2 | 07-08-2023 |  1300 |             | 
+ company2 | 07-09-2023 |  1200 |             | 
+ company2 | 07-10-2023 |  1300 |             | 
+(20 rows)
+
+-- backtracking with reclassification of rows
+-- using AFTER MATCH SKIP TO NEXT ROW
+SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ INITIAL
+ PATTERN (A+ B+)
+ DEFINE
+  A AS price > 100,
+  B AS price > 100
+);
+ company  |   tdate    | price | first_value | last_value 
+----------+------------+-------+-------------+------------
+ company1 | 07-01-2023 |   100 |             | 
+ company1 | 07-02-2023 |   200 | 07-02-2023  | 07-05-2023
+ company1 | 07-03-2023 |   150 | 07-03-2023  | 07-05-2023
+ company1 | 07-04-2023 |   140 | 07-04-2023  | 07-05-2023
+ company1 | 07-05-2023 |   150 |             | 
+ company1 | 07-06-2023 |    90 |             | 
+ company1 | 07-07-2023 |   110 | 07-07-2023  | 07-10-2023
+ company1 | 07-08-2023 |   130 | 07-08-2023  | 07-10-2023
+ company1 | 07-09-2023 |   120 | 07-09-2023  | 07-10-2023
+ company1 | 07-10-2023 |   130 |             | 
+ company2 | 07-01-2023 |    50 |             | 
+ company2 | 07-02-2023 |  2000 | 07-02-2023  | 07-05-2023
+ company2 | 07-03-2023 |  1500 | 07-03-2023  | 07-05-2023
+ company2 | 07-04-2023 |  1400 | 07-04-2023  | 07-05-2023
+ company2 | 07-05-2023 |  1500 |             | 
+ company2 | 07-06-2023 |    60 |             | 
+ company2 | 07-07-2023 |  1100 | 07-07-2023  | 07-10-2023
+ company2 | 07-08-2023 |  1300 | 07-08-2023  | 07-10-2023
+ company2 | 07-09-2023 |  1200 | 07-09-2023  | 07-10-2023
+ company2 | 07-10-2023 |  1300 |             | 
+(20 rows)
+
+-- ROWS BETWEEN CURRENT ROW AND offset FOLLOWING
+SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w,
+ count(*) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING
+ AFTER MATCH SKIP PAST LAST ROW
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | first_value | last_value | count 
+----------+------------+-------+-------------+------------+-------
+ company1 | 07-01-2023 |   100 | 07-01-2023  | 07-03-2023 |     3
+ company1 | 07-02-2023 |   200 |             |            |     0
+ company1 | 07-03-2023 |   150 |             |            |     0
+ company1 | 07-04-2023 |   140 | 07-04-2023  | 07-06-2023 |     3
+ company1 | 07-05-2023 |   150 |             |            |     0
+ company1 | 07-06-2023 |    90 |             |            |     0
+ company1 | 07-07-2023 |   110 | 07-07-2023  | 07-09-2023 |     3
+ company1 | 07-08-2023 |   130 |             |            |     0
+ company1 | 07-09-2023 |   120 |             |            |     0
+ company1 | 07-10-2023 |   130 |             |            |     0
+ company2 | 07-01-2023 |    50 | 07-01-2023  | 07-03-2023 |     3
+ company2 | 07-02-2023 |  2000 |             |            |     0
+ company2 | 07-03-2023 |  1500 |             |            |     0
+ company2 | 07-04-2023 |  1400 | 07-04-2023  | 07-06-2023 |     3
+ company2 | 07-05-2023 |  1500 |             |            |     0
+ company2 | 07-06-2023 |    60 |             |            |     0
+ company2 | 07-07-2023 |  1100 | 07-07-2023  | 07-09-2023 |     3
+ company2 | 07-08-2023 |  1300 |             |            |     0
+ company2 | 07-09-2023 |  1200 |             |            |     0
+ company2 | 07-10-2023 |  1300 |             |            |     0
+(20 rows)
+
+--
+-- Aggregates
+--
+-- using AFTER MATCH SKIP PAST LAST ROW
+SELECT company, tdate, price,
+ first_value(price) OVER w,
+ last_value(price) OVER w,
+ max(price) OVER w,
+ min(price) OVER w,
+ sum(price) OVER w,
+ avg(price) OVER w,
+ count(price) OVER w
+FROM stock
+WINDOW w AS (
+PARTITION BY company
+ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+AFTER MATCH SKIP PAST LAST ROW
+INITIAL
+PATTERN (START UP+ DOWN+)
+DEFINE
+START AS TRUE,
+UP AS price > PREV(price),
+DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | first_value | last_value | max  | min | sum  |          avg          | count 
+----------+------------+-------+-------------+------------+------+-----+------+-----------------------+-------
+ company1 | 07-01-2023 |   100 |         100 |        140 |  200 | 100 |  590 |  147.5000000000000000 |     4
+ company1 | 07-02-2023 |   200 |             |            |      |     |      |                       |     0
+ company1 | 07-03-2023 |   150 |             |            |      |     |      |                       |     0
+ company1 | 07-04-2023 |   140 |             |            |      |     |      |                       |     0
+ company1 | 07-05-2023 |   150 |             |            |      |     |      |                       |     0
+ company1 | 07-06-2023 |    90 |          90 |        120 |  130 |  90 |  450 |  112.5000000000000000 |     4
+ company1 | 07-07-2023 |   110 |             |            |      |     |      |                       |     0
+ company1 | 07-08-2023 |   130 |             |            |      |     |      |                       |     0
+ company1 | 07-09-2023 |   120 |             |            |      |     |      |                       |     0
+ company1 | 07-10-2023 |   130 |             |            |      |     |      |                       |     0
+ company2 | 07-01-2023 |    50 |          50 |       1400 | 2000 |  50 | 4950 | 1237.5000000000000000 |     4
+ company2 | 07-02-2023 |  2000 |             |            |      |     |      |                       |     0
+ company2 | 07-03-2023 |  1500 |             |            |      |     |      |                       |     0
+ company2 | 07-04-2023 |  1400 |             |            |      |     |      |                       |     0
+ company2 | 07-05-2023 |  1500 |             |            |      |     |      |                       |     0
+ company2 | 07-06-2023 |    60 |          60 |       1200 | 1300 |  60 | 3660 |  915.0000000000000000 |     4
+ company2 | 07-07-2023 |  1100 |             |            |      |     |      |                       |     0
+ company2 | 07-08-2023 |  1300 |             |            |      |     |      |                       |     0
+ company2 | 07-09-2023 |  1200 |             |            |      |     |      |                       |     0
+ company2 | 07-10-2023 |  1300 |             |            |      |     |      |                       |     0
+(20 rows)
+
+-- using AFTER MATCH SKIP TO NEXT ROW
+SELECT company, tdate, price,
+ first_value(price) OVER w,
+ last_value(price) OVER w,
+ max(price) OVER w,
+ min(price) OVER w,
+ sum(price) OVER w,
+ avg(price) OVER w,
+ count(price) OVER w
+FROM stock
+WINDOW w AS (
+PARTITION BY company
+ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+AFTER MATCH SKIP TO NEXT ROW
+INITIAL
+PATTERN (START UP+ DOWN+)
+DEFINE
+START AS TRUE,
+UP AS price > PREV(price),
+DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | first_value | last_value | max  | min  | sum  |          avg          | count 
+----------+------------+-------+-------------+------------+------+------+------+-----------------------+-------
+ company1 | 07-01-2023 |   100 |         100 |        140 |  200 |  100 |  590 |  147.5000000000000000 |     4
+ company1 | 07-02-2023 |   200 |             |            |      |      |      |                       |     0
+ company1 | 07-03-2023 |   150 |             |            |      |      |      |                       |     0
+ company1 | 07-04-2023 |   140 |         140 |         90 |  150 |   90 |  380 |  126.6666666666666667 |     3
+ company1 | 07-05-2023 |   150 |             |            |      |      |      |                       |     0
+ company1 | 07-06-2023 |    90 |          90 |        120 |  130 |   90 |  450 |  112.5000000000000000 |     4
+ company1 | 07-07-2023 |   110 |         110 |        120 |  130 |  110 |  360 |  120.0000000000000000 |     3
+ company1 | 07-08-2023 |   130 |             |            |      |      |      |                       |     0
+ company1 | 07-09-2023 |   120 |             |            |      |      |      |                       |     0
+ company1 | 07-10-2023 |   130 |             |            |      |      |      |                       |     0
+ company2 | 07-01-2023 |    50 |          50 |       1400 | 2000 |   50 | 4950 | 1237.5000000000000000 |     4
+ company2 | 07-02-2023 |  2000 |             |            |      |      |      |                       |     0
+ company2 | 07-03-2023 |  1500 |             |            |      |      |      |                       |     0
+ company2 | 07-04-2023 |  1400 |        1400 |         60 | 1500 |   60 | 2960 |  986.6666666666666667 |     3
+ company2 | 07-05-2023 |  1500 |             |            |      |      |      |                       |     0
+ company2 | 07-06-2023 |    60 |          60 |       1200 | 1300 |   60 | 3660 |  915.0000000000000000 |     4
+ company2 | 07-07-2023 |  1100 |        1100 |       1200 | 1300 | 1100 | 3600 | 1200.0000000000000000 |     3
+ company2 | 07-08-2023 |  1300 |             |            |      |      |      |                       |     0
+ company2 | 07-09-2023 |  1200 |             |            |      |      |      |                       |     0
+ company2 | 07-10-2023 |  1300 |             |            |      |      |      |                       |     0
+(20 rows)
+
+-- JOIN case
+CREATE TEMP TABLE t1 (i int, v1 int);
+CREATE TEMP TABLE t2 (j int, v2 int);
+INSERT INTO t1 VALUES(1,10);
+INSERT INTO t1 VALUES(1,11);
+INSERT INTO t1 VALUES(1,12);
+INSERT INTO t2 VALUES(2,10);
+INSERT INTO t2 VALUES(2,11);
+INSERT INTO t2 VALUES(2,12);
+SELECT * FROM t1, t2 WHERE t1.v1 <= 11 AND t2.v2 <= 11;
+ i | v1 | j | v2 
+---+----+---+----
+ 1 | 10 | 2 | 10
+ 1 | 10 | 2 | 11
+ 1 | 11 | 2 | 10
+ 1 | 11 | 2 | 11
+(4 rows)
+
+SELECT *, count(*) OVER w FROM t1, t2
+WINDOW w AS (
+ PARTITION BY t1.i
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (A)
+ DEFINE
+ A AS v1 <= 11 AND v2 <= 11
+);
+ i | v1 | j | v2 | count 
+---+----+---+----+-------
+ 1 | 10 | 2 | 10 |     1
+ 1 | 10 | 2 | 11 |     1
+ 1 | 10 | 2 | 12 |     0
+ 1 | 11 | 2 | 10 |     1
+ 1 | 11 | 2 | 11 |     1
+ 1 | 11 | 2 | 12 |     0
+ 1 | 12 | 2 | 10 |     0
+ 1 | 12 | 2 | 11 |     0
+ 1 | 12 | 2 | 12 |     0
+(9 rows)
+
+-- WITH case
+WITH wstock AS (
+  SELECT * FROM stock WHERE tdate < '2023-07-08'
+)
+SELECT tdate, price,
+first_value(tdate) OVER w,
+count(*) OVER w
+ FROM wstock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+   tdate    | price | first_value | count 
+------------+-------+-------------+-------
+ 07-01-2023 |   100 | 07-01-2023  |     4
+ 07-02-2023 |   200 |             |     0
+ 07-03-2023 |   150 |             |     0
+ 07-04-2023 |   140 |             |     0
+ 07-05-2023 |   150 |             |     0
+ 07-06-2023 |    90 |             |     0
+ 07-07-2023 |   110 |             |     0
+ 07-01-2023 |    50 | 07-01-2023  |     4
+ 07-02-2023 |  2000 |             |     0
+ 07-03-2023 |  1500 |             |     0
+ 07-04-2023 |  1400 |             |     0
+ 07-05-2023 |  1500 |             |     0
+ 07-06-2023 |    60 |             |     0
+ 07-07-2023 |  1100 |             |     0
+(14 rows)
+
+-- PREV has multiple column reference
+CREATE TEMP TABLE rpr1 (id INTEGER, i SERIAL, j INTEGER);
+INSERT INTO rpr1(id, j) SELECT 1, g*2 FROM generate_series(1, 10) AS g;
+SELECT id, i, j, count(*) OVER w
+ FROM rpr1
+ WINDOW w AS (
+ PARTITION BY id
+ ORDER BY i
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP PAST LAST ROW
+ INITIAL
+ PATTERN (START COND+)
+ DEFINE
+  START AS TRUE,
+  COND AS PREV(i + j + 1) < 10
+);
+ id | i  | j  | count 
+----+----+----+-------
+  1 |  1 |  2 |     3
+  1 |  2 |  4 |     0
+  1 |  3 |  6 |     0
+  1 |  4 |  8 |     0
+  1 |  5 | 10 |     0
+  1 |  6 | 12 |     0
+  1 |  7 | 14 |     0
+  1 |  8 | 16 |     0
+  1 |  9 | 18 |     0
+  1 | 10 | 20 |     0
+(10 rows)
+
+-- Smoke test for larger partitions.
+WITH s AS (
+ SELECT v, count(*) OVER w AS c
+ FROM (SELECT generate_series(1, 5000) v)
+ WINDOW w AS (
+  ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+  AFTER MATCH SKIP PAST LAST ROW
+  INITIAL
+  PATTERN ( r+ )
+  DEFINE r AS TRUE
+ )
+)
+-- Should be exactly one long match across all rows.
+SELECT * FROM s WHERE c > 0;
+ v |  c   
+---+------
+ 1 | 5000
+(1 row)
+
+WITH s AS (
+ SELECT v, count(*) OVER w AS c
+ FROM (SELECT generate_series(1, 5000) v)
+ WINDOW w AS (
+  ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+  AFTER MATCH SKIP PAST LAST ROW
+  INITIAL
+  PATTERN ( r )
+  DEFINE r AS TRUE
+ )
+)
+-- Every row should be its own match.
+SELECT count(*) FROM s WHERE c > 0;
+ count 
+-------
+  5000
+(1 row)
+
+--
+-- Error cases
+--
+-- row pattern definition variable name must not appear more than once
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price),
+  UP AS price > PREV(price)
+);
+ERROR:  row pattern definition variable name "up" appears more than once in DEFINE clause
+LINE 11:   UP AS price > PREV(price),
+           ^
+-- subqueries in DEFINE clause are not supported
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START LOWPRICE)
+ DEFINE
+  START AS TRUE,
+  LOWPRICE AS price < (SELECT 100)
+);
+ERROR:  cannot use subquery in DEFINE expression
+LINE 11:   LOWPRICE AS price < (SELECT 100)
+                               ^
+-- aggregates in DEFINE clause are not supported
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START LOWPRICE)
+ DEFINE
+  START AS TRUE,
+  LOWPRICE AS price < count(*)
+);
+ERROR:  aggregate functions are not allowed in DEFINE
+LINE 11:   LOWPRICE AS price < count(*)
+                               ^
+-- FRAME must start at current row when row patttern recognition is used
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+ERROR:  FRAME must start at current row when row patttern recognition is used
+-- SEEK is not supported
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ SEEK
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+ERROR:  SEEK is not supported
+LINE 8:  SEEK
+         ^
+HINT:  Use INITIAL.
+-- PREV's argument must have at least 1 column reference
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(1),
+  DOWN AS price < PREV(1)
+);
+ERROR:  row pattern navigation operation's argument must include at least one column reference
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 81e4222d26..35df8f159e 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -98,7 +98,7 @@ test: publication subscription
 # Another group of parallel tests
 # select_views depends on create_view
 # ----------
-test: select_views portals_p2 foreign_key cluster dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock indirect_toast equivclass
+test: select_views portals_p2 foreign_key cluster dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock indirect_toast equivclass rpr
 
 # ----------
 # Another group of parallel tests (JSON related)
diff --git a/src/test/regress/sql/rpr.sql b/src/test/regress/sql/rpr.sql
new file mode 100644
index 0000000000..a46abe6f0f
--- /dev/null
+++ b/src/test/regress/sql/rpr.sql
@@ -0,0 +1,467 @@
+--
+-- Test for row pattern definition clause
+--
+
+CREATE TEMP TABLE stock (
+       company TEXT,
+       tdate DATE,
+       price INTEGER
+);
+INSERT INTO stock VALUES ('company1', '2023-07-01', 100);
+INSERT INTO stock VALUES ('company1', '2023-07-02', 200);
+INSERT INTO stock VALUES ('company1', '2023-07-03', 150);
+INSERT INTO stock VALUES ('company1', '2023-07-04', 140);
+INSERT INTO stock VALUES ('company1', '2023-07-05', 150);
+INSERT INTO stock VALUES ('company1', '2023-07-06', 90);
+INSERT INTO stock VALUES ('company1', '2023-07-07', 110);
+INSERT INTO stock VALUES ('company1', '2023-07-08', 130);
+INSERT INTO stock VALUES ('company1', '2023-07-09', 120);
+INSERT INTO stock VALUES ('company1', '2023-07-10', 130);
+INSERT INTO stock VALUES ('company2', '2023-07-01', 50);
+INSERT INTO stock VALUES ('company2', '2023-07-02', 2000);
+INSERT INTO stock VALUES ('company2', '2023-07-03', 1500);
+INSERT INTO stock VALUES ('company2', '2023-07-04', 1400);
+INSERT INTO stock VALUES ('company2', '2023-07-05', 1500);
+INSERT INTO stock VALUES ('company2', '2023-07-06', 60);
+INSERT INTO stock VALUES ('company2', '2023-07-07', 1100);
+INSERT INTO stock VALUES ('company2', '2023-07-08', 1300);
+INSERT INTO stock VALUES ('company2', '2023-07-09', 1200);
+INSERT INTO stock VALUES ('company2', '2023-07-10', 1300);
+
+SELECT * FROM stock;
+
+-- basic test using PREV
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
+ nth_value(tdate, 2) OVER w AS nth_second
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+-- basic test using PREV. UP appears twice
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
+ nth_value(tdate, 2) OVER w AS nth_second
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+ UP+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+-- basic test using PREV. Use '*'
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
+ nth_value(tdate, 2) OVER w AS nth_second
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP* DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+-- basic test with none greedy pattern
+SELECT company, tdate, price, count(*) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (A A A)
+ DEFINE
+  A AS price >= 140 AND price <= 150
+);
+
+-- last_value() should remain consistent
+SELECT company, tdate, price, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+-- omit "START" in DEFINE but it is ok because "START AS TRUE" is
+-- implicitly defined. per spec.
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
+ nth_value(tdate, 2) OVER w AS nth_second
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+-- the first row start with less than or equal to 100
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (LOWPRICE UP+ DOWN+)
+ DEFINE
+  LOWPRICE AS price <= 100,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+-- second row raises 120%
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (LOWPRICE UP+ DOWN+)
+ DEFINE
+  LOWPRICE AS price <= 100,
+  UP AS price > PREV(price) * 1.2,
+  DOWN AS price < PREV(price)
+);
+
+-- using NEXT
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UPDOWN)
+ DEFINE
+  START AS TRUE,
+  UPDOWN AS price > PREV(price) AND price > NEXT(price)
+);
+
+-- using AFTER MATCH SKIP TO NEXT ROW
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ INITIAL
+ PATTERN (START UPDOWN)
+ DEFINE
+  START AS TRUE,
+  UPDOWN AS price > PREV(price) AND price > NEXT(price)
+);
+
+-- match everything
+
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP PAST LAST ROW
+ INITIAL
+ PATTERN (A+)
+ DEFINE
+  A AS TRUE
+);
+
+-- backtracking with reclassification of rows
+-- using AFTER MATCH SKIP PAST LAST ROW
+SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP PAST LAST ROW
+ INITIAL
+ PATTERN (A+ B+)
+ DEFINE
+  A AS price > 100,
+  B AS price > 100
+);
+
+-- backtracking with reclassification of rows
+-- using AFTER MATCH SKIP TO NEXT ROW
+SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ INITIAL
+ PATTERN (A+ B+)
+ DEFINE
+  A AS price > 100,
+  B AS price > 100
+);
+
+-- ROWS BETWEEN CURRENT ROW AND offset FOLLOWING
+SELECT company, tdate, price, first_value(tdate) OVER w, last_value(tdate) OVER w,
+ count(*) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING
+ AFTER MATCH SKIP PAST LAST ROW
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+--
+-- Aggregates
+--
+
+-- using AFTER MATCH SKIP PAST LAST ROW
+SELECT company, tdate, price,
+ first_value(price) OVER w,
+ last_value(price) OVER w,
+ max(price) OVER w,
+ min(price) OVER w,
+ sum(price) OVER w,
+ avg(price) OVER w,
+ count(price) OVER w
+FROM stock
+WINDOW w AS (
+PARTITION BY company
+ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+AFTER MATCH SKIP PAST LAST ROW
+INITIAL
+PATTERN (START UP+ DOWN+)
+DEFINE
+START AS TRUE,
+UP AS price > PREV(price),
+DOWN AS price < PREV(price)
+);
+
+-- using AFTER MATCH SKIP TO NEXT ROW
+SELECT company, tdate, price,
+ first_value(price) OVER w,
+ last_value(price) OVER w,
+ max(price) OVER w,
+ min(price) OVER w,
+ sum(price) OVER w,
+ avg(price) OVER w,
+ count(price) OVER w
+FROM stock
+WINDOW w AS (
+PARTITION BY company
+ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+AFTER MATCH SKIP TO NEXT ROW
+INITIAL
+PATTERN (START UP+ DOWN+)
+DEFINE
+START AS TRUE,
+UP AS price > PREV(price),
+DOWN AS price < PREV(price)
+);
+
+-- JOIN case
+CREATE TEMP TABLE t1 (i int, v1 int);
+CREATE TEMP TABLE t2 (j int, v2 int);
+INSERT INTO t1 VALUES(1,10);
+INSERT INTO t1 VALUES(1,11);
+INSERT INTO t1 VALUES(1,12);
+INSERT INTO t2 VALUES(2,10);
+INSERT INTO t2 VALUES(2,11);
+INSERT INTO t2 VALUES(2,12);
+
+SELECT * FROM t1, t2 WHERE t1.v1 <= 11 AND t2.v2 <= 11;
+
+SELECT *, count(*) OVER w FROM t1, t2
+WINDOW w AS (
+ PARTITION BY t1.i
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (A)
+ DEFINE
+ A AS v1 <= 11 AND v2 <= 11
+);
+
+-- WITH case
+WITH wstock AS (
+  SELECT * FROM stock WHERE tdate < '2023-07-08'
+)
+SELECT tdate, price,
+first_value(tdate) OVER w,
+count(*) OVER w
+ FROM wstock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+-- PREV has multiple column reference
+CREATE TEMP TABLE rpr1 (id INTEGER, i SERIAL, j INTEGER);
+INSERT INTO rpr1(id, j) SELECT 1, g*2 FROM generate_series(1, 10) AS g;
+SELECT id, i, j, count(*) OVER w
+ FROM rpr1
+ WINDOW w AS (
+ PARTITION BY id
+ ORDER BY i
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP PAST LAST ROW
+ INITIAL
+ PATTERN (START COND+)
+ DEFINE
+  START AS TRUE,
+  COND AS PREV(i + j + 1) < 10
+);
+
+-- Smoke test for larger partitions.
+WITH s AS (
+ SELECT v, count(*) OVER w AS c
+ FROM (SELECT generate_series(1, 5000) v)
+ WINDOW w AS (
+  ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+  AFTER MATCH SKIP PAST LAST ROW
+  INITIAL
+  PATTERN ( r+ )
+  DEFINE r AS TRUE
+ )
+)
+-- Should be exactly one long match across all rows.
+SELECT * FROM s WHERE c > 0;
+
+WITH s AS (
+ SELECT v, count(*) OVER w AS c
+ FROM (SELECT generate_series(1, 5000) v)
+ WINDOW w AS (
+  ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+  AFTER MATCH SKIP PAST LAST ROW
+  INITIAL
+  PATTERN ( r )
+  DEFINE r AS TRUE
+ )
+)
+-- Every row should be its own match.
+SELECT count(*) FROM s WHERE c > 0;
+
+--
+-- Error cases
+--
+
+-- row pattern definition variable name must not appear more than once
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price),
+  UP AS price > PREV(price)
+);
+
+-- subqueries in DEFINE clause are not supported
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START LOWPRICE)
+ DEFINE
+  START AS TRUE,
+  LOWPRICE AS price < (SELECT 100)
+);
+
+-- aggregates in DEFINE clause are not supported
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START LOWPRICE)
+ DEFINE
+  START AS TRUE,
+  LOWPRICE AS price < count(*)
+);
+
+-- FRAME must start at current row when row patttern recognition is used
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+-- SEEK is not supported
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ SEEK
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+-- PREV's argument must have at least 1 column reference
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ INITIAL
+ PATTERN (START UP+ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(1),
+  DOWN AS price < PREV(1)
+);
-- 
2.25.1


----Next_Part(Thu_Dec_19_15_19_50_2024_894)--
Content-Type: Text/X-Patch; charset=us-ascii
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="v24-0008-Allow-to-print-raw-parse-tree.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread

* [PATCH v5 05/10] Address space reservation for shared memory
@ 2025-06-17 09:47  Dmitrii Dolgov <9erthalion6@gmail.com>
  0 siblings, 0 replies; 213+ messages in thread

From: Dmitrii Dolgov @ 2025-06-17 09:47 UTC (permalink / raw)

Currently the shared memory layout is designed to pack everything tight
together, leaving no space between mappings for resizing. Here is how it
looks like for one mapping in /proc/$PID/maps, /dev/zero represents the
anonymous shared memory we talk about:

    00400000-00490000         /path/bin/postgres
    ...
    012d9000-0133e000         [heap]
    7f443a800000-7f470a800000 /dev/zero (deleted)
    7f470a800000-7f471831d000 /usr/lib/locale/locale-archive
    7f4718400000-7f4718401000 /usr/lib64/libstdc++.so.6.0.34
    ...

Make the layout more dynamic via splitting every shared memory segment
into two parts:

* An anonymous file, which actually contains shared memory content. Such
  an anonymous file is created via memfd_create, it lives in memory,
  behaves like a regular file and semantically equivalent to an
  anonymous memory allocated via mmap with MAP_ANONYMOUS.

* A reservation mapping, which size is much larger than required shared
  segment size. This mapping is created with flags PROT_NONE (which
  makes sure the reserved space is not used), and MAP_NORESERVE (to not
  count the reserved space against memory limits). The anonymous file is
  mapped into this reservation mapping.

The resulting layout looks like this:

    00400000-00490000         /path/bin/postgres
    ...
    3f526000-3f590000 rw-p 		[heap]
    7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted) -- anon file
    7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted) -- reservation
    7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
    7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34

To resize a shared memory segment in this layout it's possible to use ftruncate
on the anonymous file, adjusting access permissions on the reserved space as
needed.

This approach also do not impact the actual memory usage as reported by
the kernel. Here is the output of /proc/$PID/status for the master
version with shared_buffers = 128 MB:

    // Peak virtual memory size, which is described as total pages
    // mapped in mm_struct. It corresponds to the mapped reserved space
    // and is the only number that grows with it.
    VmPeak:          2043192 kB
    // Size of memory portions. It contains RssAnon + RssFile + RssShmem
    VmRSS:             22908 kB
    // Size of resident anonymous memory
    RssAnon:             768 kB
    // Size of resident file mappings
    RssFile:           10364 kB
    // Size of resident shmem memory (includes SysV shm, mapping of tmpfs and
    // shared anonymous mappings)
    RssShmem:          11776 kB

Here is the same for the patch when reserving 20GB of space:

    VmPeak:         21255824 kB
    VmRSS:             25020 kB
    RssAnon:             768 kB
    RssFile:           10812 kB
    RssShmem:          13440 kB

Cgroup v2 doesn't have any problems with that as well. To verify a new cgroup
was created with the memory limit 256 MB, then PostgreSQL was launched withing
this cgroup with shared_buffers = 128 MB:

    $ cd /sys/fs/cgroup
    $ mkdir postgres
    $ cd postres
    $ echo 268435456 > memory.max

    $ echo $MASTER_PID_SHELL > cgroup.procs
    # postgres from the master branch has being successfully launched
    #  from that shell
    $ cat memory.current
    17465344 (~16.6 MB)
    # stop postgres

    $ echo $PATCH_PID_SHELL > cgroup.procs
    # postgres from the patch has being successfully launched from that shell
    $ cat memory.current
    20770816 (~19.8 MB)

To control the amount of space reserved a new GUC max_available_memory
is introduced. Ideally it should be based on the maximum available
memory, hense the name.

There are also few unrelated advantages of using anon files:

* We've got a file descriptor, which could be used for regular file
  operations (modification, truncation, you name it).

* The file could be given a name, which improves readability when it
  comes to process maps.

* By default, Linux will not add file-backed shared mappings into a core dump,
  making it more convenient to work with them in PostgreSQL: no more huge dumps
  to process.

The downside is that memfd_create is Linux specific.
---
 src/backend/port/sysv_shmem.c       | 290 ++++++++++++++++++++++------
 src/backend/port/win32_shmem.c      |   2 +-
 src/backend/storage/ipc/ipci.c      |   5 +-
 src/backend/storage/ipc/shmem.c     |   2 +-
 src/backend/utils/init/globals.c    |   1 +
 src/backend/utils/misc/guc_tables.c |  14 ++
 src/include/miscadmin.h             |   1 +
 src/include/portability/mem.h       |   2 +-
 src/include/storage/pg_shmem.h      |   5 +-
 9 files changed, 262 insertions(+), 60 deletions(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 56af0231d24..363ddfd1fca 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -97,10 +97,12 @@ void	   *UsedShmemSegAddr = NULL;
 typedef struct AnonymousMapping
 {
 	int shmem_segment;
-	Size shmem_size; 			/* Size of the mapping */
+	Size shmem_size; 			/* Size of the actually used memory */
+	Size shmem_reserved; 		/* Size of the reserved mapping */
 	Pointer shmem; 				/* Pointer to the start of the mapped memory */
 	Pointer seg_addr; 			/* SysV shared memory for the header */
 	unsigned long seg_id; 		/* IPC key */
+	int segment_fd; 			/* fd for the backing anon file */
 } AnonymousMapping;
 
 static AnonymousMapping Mappings[ANON_MAPPINGS];
@@ -108,6 +110,49 @@ static AnonymousMapping Mappings[ANON_MAPPINGS];
 /* Keeps track of used mapping segments */
 static int next_free_segment = 0;
 
+/*
+ * Anonymous mapping layout we use looks like this:
+ *
+ * 00400000-00c2a000 r-xp 			/bin/postgres
+ * ...
+ * 3f526000-3f590000 rw-p 			[heap]
+ * 7fbd827fe000-7fbd8bdde000 rw-s 	/memfd:main (deleted)
+ * 7fbd8bdde000-7fbe82800000 ---s 	/memfd:main (deleted)
+ * 7fbe82800000-7fbe90670000 r--p 	/usr/lib/locale/locale-archive
+ * 7fbe90800000-7fbe90941000 r-xp 	/usr/lib64/libstdc++.so.6.0.34
+ * ...
+ *
+ * We need to place shared memory mappings in such a way, that there will be
+ * gaps between them in the address space. Those gaps have to be large enough
+ * to resize the mapping up to certain size, without counting towards the total
+ * memory consumption.
+ *
+ * To achieve this, for each shared memory segment we first create an anonymous
+ * file of specified size using memfd_create, which will accomodate actual
+ * shared memory mapping content. It is represented by the first /memfd:main
+ * with rw permissions. Then we create a mapping for this file using mmap, with
+ * size much larger than required and flags PROT_NONE (allows to make sure the
+ * reserved space will not be used) and MAP_NORESERVE (prevents the space from
+ * being counted against memory limits). The mapping serves as an address space
+ * reservation, into which shared memory segment can be extended and is
+ * represented by the second /memfd:main with no permissions.
+ *
+ * The reserved space for each segment is calculated as a fraction of the total
+ * reserved space (MaxAvailableMemory), as specified in the SHMEM_RESIZE_RATIO
+ * array.
+ */
+static double SHMEM_RESIZE_RATIO[1] = {
+	1.0, 									/* MAIN_SHMEM_SLOT */
+};
+
+/*
+ * Flag telling that we have decided to use huge pages.
+ *
+ * XXX: It's possible to use GetConfigOption("huge_pages_status", false, false)
+ * instead, but it feels like an overkill.
+ */
+static bool huge_pages_on = false;
+
 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
 static void IpcMemoryDetach(int status, Datum shmaddr);
 static void IpcMemoryDelete(int status, Datum shmId);
@@ -503,19 +548,20 @@ PGSharedMemoryAttach(IpcMemoryId shmId,
  * hugepage sizes, we might want to think about more invasive strategies,
  * such as increasing shared_buffers to absorb the extra space.
  *
- * Returns the (real, assumed or config provided) page size into
- * *hugepagesize, and the hugepage-related mmap flags to use into
- * *mmap_flags if requested by the caller.  If huge pages are not supported,
- * *hugepagesize and *mmap_flags are set to 0.
+ * Returns the (real, assumed or config provided) page size into *hugepagesize,
+ * the hugepage-related mmap and memfd flags to use into *mmap_flags and
+ * *memfd_flags if requested by the caller. If huge pages are not supported,
+ * *hugepagesize, *mmap_flags and *memfd_flags are set to 0.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 #ifdef MAP_HUGETLB
 
 	Size		default_hugepagesize = 0;
 	Size		hugepagesize_local = 0;
 	int			mmap_flags_local = 0;
+	int			memfd_flags_local = 0;
 
 	/*
 	 * System-dependent code to find out the default huge page size.
@@ -574,6 +620,7 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	}
 
 	mmap_flags_local = MAP_HUGETLB;
+	memfd_flags_local = MFD_HUGETLB;
 
 	/*
 	 * On recent enough Linux, also include the explicit page size, if
@@ -584,7 +631,16 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 	{
 		int			shift = pg_ceil_log2_64(hugepagesize_local);
 
-		mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
+	}
+#endif
+
+#if defined(MFD_HUGE_MASK) && defined(MFD_HUGE_SHIFT)
+	if (hugepagesize_local != default_hugepagesize)
+	{
+		int			shift = pg_ceil_log2_64(hugepagesize_local);
+
+		memfd_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
 	}
 #endif
 
@@ -593,6 +649,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*mmap_flags = mmap_flags_local;
 	if (hugepagesize)
 		*hugepagesize = hugepagesize_local;
+	if (memfd_flags)
+		*memfd_flags = memfd_flags_local;
 
 #else
 
@@ -600,6 +658,8 @@ GetHugePageSize(Size *hugepagesize, int *mmap_flags)
 		*hugepagesize = 0;
 	if (mmap_flags)
 		*mmap_flags = 0;
+	if (memfd_flags)
+		*memfd_flags = 0;
 
 #endif							/* MAP_HUGETLB */
 }
@@ -625,72 +685,90 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
  * Creates an anonymous mmap()ed shared memory segment.
  *
  * This function will modify mapping size to the actual size of the allocation,
- * if it ends up allocating a segment that is larger than requested.
+ * if it ends up allocating a segment that is larger than requested. If needed,
+ * it also rounds up the mapping reserved size to be a multiple of huge page
+ * size.
+ *
+ * Note that we do not fallback from huge pages to regular pages in this
+ * function, this decision was already made in ReserveAnonymousMemory and we
+ * stick to it.
  */
 static void
 CreateAnonymousSegment(AnonymousMapping *mapping)
 {
 	Size		allocsize = mapping->shmem_size;
 	void	   *ptr = MAP_FAILED;
-	int			mmap_errno = 0;
+	int			save_errno = 0;
+	int			mmap_flags = PG_MMAP_FLAGS, memfd_flags = 0;
+
+	elog(DEBUG1, "segment[%s]: size %zu, reserved %zu",
+		 MappingName(mapping->shmem_segment), mapping->shmem_size,
+		 mapping->shmem_reserved);
 
 #ifndef MAP_HUGETLB
-	/* PGSharedMemoryCreate should have dealt with this case */
-	Assert(huge_pages != HUGE_PAGES_ON);
+	/* PrepareHugePages should have dealt with this case */
+	Assert(huge_pages != HUGE_PAGES_ON && !huge_pages_on);
 #else
-	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	if (huge_pages_on)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
-		int			mmap_flags;
 
-		GetHugePageSize(&hugepagesize, &mmap_flags);
+		/* Make sure nothing is messed up */
+		Assert(huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY);
+
+		/* Round up the request size to a suitable large value */
+		GetHugePageSize(&hugepagesize, &mmap_flags, &memfd_flags);
 
 		if (allocsize % hugepagesize != 0)
 			allocsize += hugepagesize - (allocsize % hugepagesize);
 
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-		mmap_errno = errno;
-		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-		{
-			DebugMappings();
-			elog(DEBUG1, "segment[%s]: mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 MappingName(mapping->shmem_segment), allocsize);
-		}
+		/*
+		 * The reserved space is multiple of BLCKSZ. We know the huge page
+		 * size, round up the reserved space to it.
+		 */
+		mapping->shmem_reserved = mapping->shmem_reserved + hugepagesize -
+			(mapping->shmem_reserved % hugepagesize);
+
+		/* Verify that the new size is withing the reserved boundaries */
+		if (mapping->shmem_reserved < mapping->shmem_size)
+			ereport(ERROR,
+					(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+					 errmsg("not enough shared memory is reserved"),
+					 errhint("You may need to increase \"max_available_memory\".")));
+
+		mmap_flags = PG_MMAP_FLAGS | mmap_flags;
 	}
 #endif
 
 	/*
-	 * Report whether huge pages are in use.  This needs to be tracked before
-	 * the second mmap() call if attempting to use huge pages failed
-	 * previously.
+	 * Prepare an anonymous file backing the segment. Its size will be
+	 * specified later via ftruncate.
+	 *
+	 * The file behaves like a regular file, but lives in memory. Once all
+	 * references to the file are dropped,  it is automatically released.
+	 * Anonymous memory is used for all backing pages of the file, thus it has
+	 * the same semantics as anonymous memory allocations using mmap with the
+	 * MAP_ANONYMOUS flag.
 	 */
-	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
-					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	mapping->segment_fd = memfd_create(MappingName(mapping->shmem_segment),
+									   memfd_flags);
 
-	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
+	/*
+	 * Specify the segment file size using allocsize, which contains
+	 * potentially modified value.
+	 */
+	if(ftruncate(mapping->segment_fd, allocsize) == -1)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = mapping->shmem_size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   PG_MMAP_FLAGS, -1, 0);
-		mmap_errno = errno;
-	}
+		save_errno = errno;
 
-	if (ptr == MAP_FAILED)
-	{
-		errno = mmap_errno;
 		DebugMappings();
+		close(mapping->segment_fd);
+
+		errno = save_errno;
 		ereport(FATAL,
-				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+				(errmsg("segment[%s]: could not truncate anonymous file: %m",
 						MappingName(mapping->shmem_segment)),
-				 (mmap_errno == ENOMEM) ?
+				 (save_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
 						 "swap space, or huge pages. To reduce the request size "
@@ -700,10 +778,112 @@ CreateAnonymousSegment(AnonymousMapping *mapping)
 						 allocsize) : 0));
 	}
 
+	elog(DEBUG1, "segment[%s]: mmap(%zu)",
+		 MappingName(mapping->shmem_segment), allocsize);
+
+	/*
+	 * Create a reservation mapping.
+	 */
+	ptr = mmap(NULL, mapping->shmem_reserved, PROT_NONE,
+			   mmap_flags | MAP_NORESERVE, mapping->segment_fd, 0);
+	save_errno = errno;
+
+	if (ptr == MAP_FAILED)
+	{
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not map anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
+	/* Make the memory accessible */
+	if(mprotect(ptr, allocsize, PROT_READ | PROT_WRITE) == -1)
+	{
+		save_errno = errno;
+		DebugMappings();
+
+		errno = save_errno;
+		ereport(FATAL,
+				(errmsg("segment[%s]: could not mprotect anonymous shared memory: %m",
+						MappingName(mapping->shmem_segment))));
+	}
+
 	mapping->shmem = ptr;
 	mapping->shmem_size = allocsize;
 }
 
+/*
+ * PrepareHugePages
+ *
+ * Figure out if there are enough huge pages to allocate all shared memory
+ * segments, and report that information via huge_pages_status and
+ * huge_pages_on. It needs to be called before creating shared memory segments.
+ *
+ * It is necessary to maintain the same semantic (simple on/off) for
+ * huge_pages_status, even if there are multiple shared memory segments: all
+ * segments either use huge pages or not, there is no mix of segments with
+ * different page size. The latter might be actually beneficial, in particular
+ * because only some segments may require large amount of memory, but for now
+ * we go with a simple solution.
+ */
+void
+PrepareHugePages()
+{
+	void	   *ptr = MAP_FAILED;
+
+	/* Reset to handle reinitialization */
+	next_free_segment = 0;
+
+	/* Complain if hugepages demanded but we can't possibly support them */
+#if !defined(MAP_HUGETLB)
+	if (huge_pages == HUGE_PAGES_ON)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("huge pages not supported on this platform")));
+#else
+	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
+	{
+		Size		hugepagesize, total_size = 0;
+		int			mmap_flags;
+
+		GetHugePageSize(&hugepagesize, &mmap_flags, NULL);
+
+		/*
+		 * Figure out how much memory is needed for all segments, keeping in
+		 * mind that for every segment this value will be rounding up by the
+		 * huge page size. The resulting value will be used to probe memory and
+		 * decide whether we will allocate huge pages or not.
+		 */
+		for(int segment = 0; segment < ANON_MAPPINGS; segment++)
+		{
+			int	numSemas;
+			Size segment_size = CalculateShmemSize(&numSemas, segment);
+
+			if (segment_size % hugepagesize != 0)
+				segment_size += hugepagesize - (segment_size % hugepagesize);
+
+			total_size += segment_size;
+		}
+
+		/* Map total amount of memory to test its availability. */
+		elog(DEBUG1, "reserving space: probe mmap(%zu) with MAP_HUGETLB",
+					 total_size);
+		ptr = mmap(NULL, total_size, PROT_NONE,
+				   PG_MMAP_FLAGS | MAP_ANONYMOUS | mmap_flags, -1, 0);
+	}
+#endif
+
+	/*
+	 * Report whether huge pages are in use. This needs to be tracked before
+	 * creating shared memory segments.
+	 */
+	SetConfigOption("huge_pages_status", (ptr == MAP_FAILED) ? "off" : "on",
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+	huge_pages_on = ptr != MAP_FAILED;
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -746,7 +926,7 @@ PGSharedMemoryCreate(Size size,
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	struct stat statbuf;
-	Size		sysvsize;
+	Size		sysvsize, total_reserved;
 	AnonymousMapping *mapping = &Mappings[next_free_segment];
 
 	/*
@@ -760,14 +940,6 @@ PGSharedMemoryCreate(Size size,
 				 errmsg("could not stat data directory \"%s\": %m",
 						DataDir)));
 
-	/* Complain if hugepages demanded but we can't possibly support them */
-#if !defined(MAP_HUGETLB)
-	if (huge_pages == HUGE_PAGES_ON)
-		ereport(ERROR,
-				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-				 errmsg("huge pages not supported on this platform")));
-#endif
-
 	/* For now, we don't support huge pages in SysV memory */
 	if (huge_pages == HUGE_PAGES_ON && shared_memory_type != SHMEM_TYPE_MMAP)
 		ereport(ERROR,
@@ -776,8 +948,16 @@ PGSharedMemoryCreate(Size size,
 
 	/* Room for a header? */
 	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
+	/* Prepare the mapping information */
 	mapping->shmem_size = size;
 	mapping->shmem_segment = next_free_segment;
+	total_reserved = (Size) MaxAvailableMemory * BLCKSZ;
+	mapping->shmem_reserved = total_reserved * SHMEM_RESIZE_RATIO[next_free_segment];
+
+	/* Round up to be a multiple of BLCKSZ */
+	mapping->shmem_reserved = mapping->shmem_reserved + BLCKSZ -
+		(mapping->shmem_reserved % BLCKSZ);
 
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index 4dee856d6bd..732fedee87e 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -627,7 +627,7 @@ pgwin32_ReserveSharedMemoryRegion(HANDLE hChild)
  * use GetLargePageMinimum() instead.
  */
 void
-GetHugePageSize(Size *hugepagesize, int *mmap_flags)
+GetHugePageSize(Size *hugepagesize, int *mmap_flags, int *memfd_flags)
 {
 	if (hugepagesize)
 		*hugepagesize = 0;
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 8b38e985327..b60f7ef9ce2 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -206,6 +206,9 @@ CreateSharedMemoryAndSemaphores(void)
 
 	Assert(!IsUnderPostmaster);
 
+	/* Decide if we use huge pages or regular size pages */
+	PrepareHugePages();
+
 	for(int segment = 0; segment < ANON_MAPPINGS; segment++)
 	{
 		/* Compute the size of the shared-memory block */
@@ -377,7 +380,7 @@ InitializeShmemGUCs(void)
 	/*
 	 * Calculate the number of huge pages required.
 	 */
-	GetHugePageSize(&hp_size, NULL);
+	GetHugePageSize(&hp_size, NULL, NULL);
 	if (hp_size != 0)
 	{
 		Size		hp_required;
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 72255a1c5ca..8d025f0e907 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -817,7 +817,7 @@ pg_get_shmem_pagesize(void)
 	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
 
 	if (huge_pages_status == HUGE_PAGES_ON)
-		GetHugePageSize(&os_page_size, NULL);
+		GetHugePageSize(&os_page_size, NULL, NULL);
 
 	return os_page_size;
 }
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index d31cb45a058..90d3feb547c 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -140,6 +140,7 @@ int			max_parallel_maintenance_workers = 2;
  * register background workers.
  */
 int			NBuffers = 16384;
+int			MaxAvailableMemory = 524288;
 int			MaxConnections = 100;
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index f04bfedb2fd..a221e446d6a 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -2376,6 +2376,20 @@ struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"max_available_memory", PGC_SIGHUP, RESOURCES_MEM,
+			gettext_noop("Sets the upper limit for the shared_buffers value."),
+			gettext_noop("Shared memory could be resized at runtime, this "
+						 "parameters sets the upper limit for it, beyond which "
+						 "resizing would not be supported. Normally this value "
+						 "would be the same as the total available memory."),
+			GUC_UNIT_BLOCKS
+		},
+		&MaxAvailableMemory,
+		524288, 16, INT_MAX / 2,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"vacuum_buffer_usage_limit", PGC_USERSET, RESOURCES_MEM,
 			gettext_noop("Sets the buffer pool size for VACUUM, ANALYZE, and autovacuum."),
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 1bef98471c3..a0c37a7749e 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -173,6 +173,7 @@ extern PGDLLIMPORT char *DataDir;
 extern PGDLLIMPORT int data_directory_mode;
 
 extern PGDLLIMPORT int NBuffers;
+extern PGDLLIMPORT int MaxAvailableMemory;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
 extern PGDLLIMPORT int max_worker_processes;
diff --git a/src/include/portability/mem.h b/src/include/portability/mem.h
index ef9800732d9..40588ff6968 100644
--- a/src/include/portability/mem.h
+++ b/src/include/portability/mem.h
@@ -38,7 +38,7 @@
 #define MAP_NOSYNC			0
 #endif
 
-#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+#define PG_MMAP_FLAGS			(MAP_SHARED|MAP_HASSEMAPHORE)
 
 /* Some really old systems don't define MAP_FAILED. */
 #ifndef MAP_FAILED
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index 2348c59b5a0..79b0b1ef9eb 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -61,6 +61,7 @@ extern PGDLLIMPORT int shared_memory_type;
 extern PGDLLIMPORT int huge_pages;
 extern PGDLLIMPORT int huge_page_size;
 extern PGDLLIMPORT int huge_pages_status;
+extern PGDLLIMPORT int MaxAvailableMemory;
 
 /* Possible values for huge_pages and huge_pages_status */
 typedef enum
@@ -104,7 +105,9 @@ extern PGShmemHeader *PGSharedMemoryCreate(Size size,
 										   PGShmemHeader **shim);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
-extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags,
+							int *memfd_flags);
+void PrepareHugePages(void);
 
 /* The main segment, contains everything except buffer blocks and related data. */
 #define MAIN_SHMEM_SEGMENT 0
-- 
2.49.0


--bwrlgp6w2ubxykjq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment;
	filename="v5-0006-Introduce-multiple-shmem-segments-for-shared-buff.patch"



^ permalink  raw  reply  [nested|flat] 213+ messages in thread


end of thread, other threads:[~2025-06-17 09:47 UTC | newest]

Thread overview: 213+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-10-16 18:21 [PATCH v4 2/8] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2024-12-19 06:06 [PATCH v24 7/8] Row pattern recognition patch (tests). Tatsuo Ishii <ishii@postgresql.org>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>
2025-06-17 09:47 [PATCH v5 05/10] Address space reservation for shared memory Dmitrii Dolgov <9erthalion6@gmail.com>

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox