From 7c5a5dfc0d28cc07800421224fb6b1cdbbf5a7a1 Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Wed, 7 Oct 2026 18:02:49 +0530
Subject: [PATCH v20261203 05/10] Resizable shared memory structures

Resizable shared memory structures can be requested by specifying a new
member ShmemStructOpts::maximum_size. At startup, we reserve address
space worth maximum_size in the
shared memory segment and allocate memory pages covering initial size of
the structure. It is expected that the subsystem which creates a
resizable structure would initialize only the memory worth its initial
size given by ShmemStructOpts::size. As the structure is resized using
ShmemResizeStruct() memory is freed or allocated in chunks of memory
pages when shrinking and expanding the structure respectively. Optional
ShmemStructOpts::minimum_size specification for resizable shared memory
structures allows us to enforce that a resizable structure cannot be
shrunk below a certain size. If minimum_size is not specified for a
resizable structure, it the minimum size defaults to 0. Two additional
columns are added to pg_shmem_allocations view to report minimum and
maximum size respectively.

The structure for which ShmemStructOpts::maximum_size is not specified
or is set to 0 is considered as a fixed size structure.  Existing calls
to ShmemRequestStruct() requsting fixed size structures need no change.
For fixed-size structures, the minimum size and maximum size are set to
the initial size specified in ShmemRequestStructOpts::size. This makes
maximum size and minimum size reported in pg_shmem_allocations view
semantically consistent for both fixed-size and resizable structures. As
a side effect, a request which specifies same minimum_size and
maximum_size will be treated as a fixed size structure.

Creating anonymous shared memory segment with resizable structures
==================================================================

All the shared memory requests collected at the startup are collated
into subsegments (PGShmemSubsegment's) each of which ends with only one
resizable structure, except the last subsegment which may not have any
resizable structure. These subsegments are laid out in the shared memory
segment one after the other allocating memory for all the fixed size
structures and the initial size of the resizable structure. The
unused address space of the resizable structure is rendered
inaccessible. Resizable structures can only be created at startup since
the extra memory reserved for the late allocations is small enough not
to require any resizing for saving memory.

Minimum, maximum and initial sizes of main shared memory area
=============================================================

With the addition of resizable shared structures, the main shared memory
area has three sizes to be tracked:
 - a. the minimum amount of shared memory that will always be needed
 - b. the maximum amount of shared memory that may be allocated when all
   the resizable structures have grown to their maximum size. It is also
   is the size of the address space reserved for the main shared memory
   area.
 - c. the amount of memory allocated at the server startup i.e. initial
   allocation.

mmap needs to use the maximum size to reserve enough address space to
accomodate all the shared structures. But a DBA may provision only the
memory required at the startup initially and increase or descrease the
memory provision as the demand changes.

These three sizes are reported as GUCs shared_memory_minimum_size,
shared_memory_maximum_size and shared_memory_initial_size respectively.
They replace the old GUC shared_memory_size which used to report both
size of the main shared memory area and amount of memory required in it.
Since these two things are not the same anymore, a single GUC is not
sufficient.  These GUCs help DBAs to estimate memory to be provisioned
at the startup and during run time as the resizable structures change
their sizes.

Portability
===========

Resizable shared structures feature depends upon existence of function
madvise() and constants MADV_REMOVE and MADV_WRITE_POPULATE.  On the
platforms which do not have these or the shared memory types (e.g.
Sys-V) which do not provide ability to free or allocate parts of shared
memory, we disable this feature. A run time GUC have_resizable_shmem
indicates whether a running server supports resizable structures or not.

The commit introduces a compile time flag HAVE_RESIZABLE_SHMEM which is
defined if MADV_REMOVE and MADV_WRITE_POPULATE exist. We don't check
existence of madvise separately, since existence of the constants
implies existence of the function. HAVE_RESIZABLE_SHMEM is not defined
in EXEC_BACKEND builds since that's largely used for Windows where the
APIs to free and allocate memory from and to a given address space are
not known to the author right now. Given that PostgreSQL is used widely
on Linux (with shared memory type mmap), providing this feature on Linux
benefits most of its users.  Once we figure out the required Windows
APIs, we will support this feature on Windows as well.

Prohibiting access to the unused portion of a resizable structure
================================================================

We provide ShmemProtectStruct() to add protections on the address space
reserved for a resizable shared memory structure so that the address
space upto its current size is accessible whereas the part beyond that
is inaccessible. Since these protections are backend specific, the
subsystem using the resizable shared memory structures has to make sure
to call ShmemProtectStruct() after every resize before any backend tries
to access the portion of the structure between old and the new size.
This can coordinated using ProcSignalBarrier mechanism in a running
backend.

Since the Postmaster is not part of the ProcSignalBarrier mechanism, it
requires a different mechanism to let Postmaster adjust its protections
after resizing a shared structure. But Postmaster usually wouldn't need
to access resizable structures. So instead of developing a new mechanism
we render the resizable structures inaccessible in Postmaster by
protecting the entire resizable structures (more accurately the whole
memory pages of the structure) in Postmaster. This means that a new
forked backend can not access the resizable shared memory structures
without reapplying the protections according to the latest sizes of
these structures.

Following points need more discussion.

Discussion points
=================

adding initial protections in forked case
----------------------------------------------------------------------
When a backend starts, it needs to add shmem protections it in such a
way that a ProcSignalBarrier conveying the protection change is not
missed. Hence we do it along side InitLocalDataChecksumState(). This has
two problems 1. it delays backend startup process and 2. it loosely ties
resizable shared memory structure to ProcSignalBarrier mechanim. Do we
consider the complexity worth it?  Is there any other way to do it
without these two drawbacks?

Further, we call ShmemReprotectResizableStructs() twice in the startup
sequence, once immediately after the place where
AttachSharedMemoryStructs() would be called in EXEC_BACKEND case and
then second time after ProcSignalInit(). The first one is needed so that
the processes can access the resizable structures safely. The second is
needed for the reasons mentioned there. But a change in the protection
during these calls will be missed by the backend and thus lead to
hazardous access. Can we avoid it? If ProcSignalInit() were to be called
nearer to the InitProcess(), it may make calling
ShmemReprotectResizeStructs() easier.

Protection in the resizing backend vs other backends
----------------------------------------------------
The patch provides an API to protect the address spaces not used because
of current size of the resizable structures in every backend. Since
every backend has to protect its own address space, a separate API is
required. But at the same time, in some cases the resize operation
itself needs to change the protection (e.g. when expanding the
structure). So there's some asymmetry between the moment when the
resizing backend adds protection and when other backends add it. That
doesn't affect end result since adding this protection is an idempotent
operation. But still there's some ugliness involved. This part also
needs more discussion.

HAVE_RESIZABLE_SHMEM and have_resizable_shmem
---------------------------------------------
The patch defines a build time macro HAVE_RESIZABLE_SHMEM to avoid
compilation failure on a build platform where the required system calls
or constants are not available. But we also need a run time check to see
whether the shared memory type being used allows resizing. Hence we
provide a GUC have_resizable_shmem which tells whether a running server
supports resizable shared memory or not. Most of the code which deals
with the shared memory is under HAVE_RESIZABLE_SHMEM, but there is some
related to resizable shared memory outside the macro as well. For
example, the members maximum_size, minimum_size are not under this
macro. This is mostly to allow writing readable code in both the modes
and still provide the same user visible views etc. This division of code
within and without macro needs more discussion.

Idea of using mmap to reserve address space in shared memory segments
and allocating memory within that address space on demand was proposed
by Dmitry Dolgov <9erthalion6@gmail.com>.

Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Reviewed-by: Matthias van de Meent <boekewurm+postgres@gmail.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
 configure                                     |  38 +
 configure.ac                                  |   5 +
 doc/src/sgml/config.sgml                      | 102 ++-
 doc/src/sgml/ref/postgres-ref.sgml            |   8 +-
 doc/src/sgml/runtime.sgml                     |   9 +-
 doc/src/sgml/system-views.sgml                |  57 +-
 doc/src/sgml/xfunc.sgml                       | 111 ++-
 meson.build                                   |  17 +
 src/backend/bootstrap/bootstrap.c             |   8 +-
 src/backend/port/sysv_shmem.c                 | 524 ++++++++++++-
 src/backend/port/win32_shmem.c                | 128 ++-
 src/backend/postmaster/auxprocess.c           |  46 +-
 src/backend/postmaster/postmaster.c           |  18 +-
 src/backend/storage/ipc/ipci.c                | 159 +++-
 src/backend/storage/ipc/shmem.c               | 738 +++++++++++++++++-
 src/backend/storage/lmgr/lwlock.c             |   6 +-
 src/backend/storage/lmgr/proc.c               |  22 +
 src/backend/tcop/postgres.c                   |  10 +-
 src/backend/utils/init/postinit.c             |  10 +
 src/backend/utils/misc/guc_parameters.dat     |  57 +-
 src/backend/utils/misc/guc_tables.c           |  15 +-
 src/include/catalog/pg_proc.dat               |   4 +-
 src/include/pg_config.h.in                    |  12 +
 src/include/pg_config_manual.h                |  14 +
 src/include/storage/ipc.h                     |   8 +-
 src/include/storage/pg_shmem.h                |  37 +-
 src/include/storage/shmem.h                   |  27 +-
 src/include/storage/shmem_internal.h          |   3 +-
 src/test/modules/test_shmem/Makefile          |   3 +-
 src/test/modules/test_shmem/meson.build       |   2 +
 .../t/002_resizable_shmem_struct.pl           | 576 ++++++++++++++
 .../modules/test_shmem/test_resizable_shmem.c | 443 +++++++++++
 .../modules/test_shmem/test_resizable_shmem.h |  18 +
 .../modules/test_shmem/test_shmem--1.0.sql    |  62 ++
 src/test/modules/test_shmem/test_shmem.c      |  35 +-
 src/test/regress/expected/rules.out           |   7 +-
 src/tools/pgindent/typedefs.list              |   1 +
 37 files changed, 3147 insertions(+), 193 deletions(-)
 create mode 100644 src/test/modules/test_shmem/t/002_resizable_shmem_struct.pl
 create mode 100644 src/test/modules/test_shmem/test_resizable_shmem.c
 create mode 100644 src/test/modules/test_shmem/test_resizable_shmem.h

diff --git a/configure b/configure
index f3b135c95ca..200731b1515 100755
--- a/configure
+++ b/configure
@@ -16519,6 +16519,44 @@ cat >>confdefs.h <<_ACEOF
 _ACEOF
 
 
+# mmap and madvise constants needed for resizable shared memory. See similar checks in meson.build for explanation of why these checks are here.
+ac_fn_c_check_decl "$LINENO" "MAP_NORESERVE" "ac_cv_have_decl_MAP_NORESERVE" "#include <sys/mman.h>
+"
+if test "x$ac_cv_have_decl_MAP_NORESERVE" = xyes; then :
+  ac_have_decl=1
+else
+  ac_have_decl=0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_MAP_NORESERVE $ac_have_decl
+_ACEOF
+
+ac_fn_c_check_decl "$LINENO" "MADV_POPULATE_WRITE" "ac_cv_have_decl_MADV_POPULATE_WRITE" "#include <sys/mman.h>
+"
+if test "x$ac_cv_have_decl_MADV_POPULATE_WRITE" = xyes; then :
+  ac_have_decl=1
+else
+  ac_have_decl=0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_MADV_POPULATE_WRITE $ac_have_decl
+_ACEOF
+
+ac_fn_c_check_decl "$LINENO" "MADV_REMOVE" "ac_cv_have_decl_MADV_REMOVE" "#include <sys/mman.h>
+"
+if test "x$ac_cv_have_decl_MADV_REMOVE" = xyes; then :
+  ac_have_decl=1
+else
+  ac_have_decl=0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_MADV_REMOVE $ac_have_decl
+_ACEOF
+
+
 ac_fn_c_check_func "$LINENO" "explicit_bzero" "ac_cv_func_explicit_bzero"
 if test "x$ac_cv_func_explicit_bzero" = xyes; then :
   $as_echo "#define HAVE_EXPLICIT_BZERO 1" >>confdefs.h
diff --git a/configure.ac b/configure.ac
index 18bbe596612..075541fd8f0 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1927,6 +1927,11 @@ AC_CHECK_DECLS([memset_s], [], [], [#define __STDC_WANT_LIB_EXT1__ 1
 # This is probably only present on macOS, but may as well check always
 AC_CHECK_DECLS(F_FULLFSYNC, [], [], [#include <fcntl.h>])
 
+# mmap and madvise constants needed for resizable shared memory. See similar checks in meson.build for explanation of why these checks are here.
+AC_CHECK_DECLS([MAP_NORESERVE], [], [], [#include <sys/mman.h>])
+AC_CHECK_DECLS([MADV_POPULATE_WRITE], [], [], [#include <sys/mman.h>])
+AC_CHECK_DECLS([MADV_REMOVE], [], [], [#include <sys/mman.h>])
+
 AC_REPLACE_FUNCS(m4_normalize([
 	explicit_bzero
 	getopt
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index a4b38a2876a..8073c47d43e 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -12509,6 +12509,20 @@ dynamic_library_path = '/usr/local/lib/postgresql:$libdir'
       </listitem>
      </varlistentry>
 
+     <varlistentry id="guc-have-resizable-shmem" xreflabel="have_resizable_shmem">
+      <term><varname>have_resizable_shmem</varname> (<type>boolean</type>)
+      <indexterm>
+       <primary><varname>have_resizable_shmem</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+       <para>
+        Reports whether <productname>PostgreSQL</productname> supports <link
+        linkend="xfunc-shared-addin-resizable">Resizable shared memory structures</link>.
+       </para>
+      </listitem>
+     </varlistentry>
+
      <varlistentry id="guc-huge-pages-status" xreflabel="huge_pages_status">
       <term><varname>huge_pages_status</varname> (<type>enum</type>)
       <indexterm>
@@ -12688,32 +12702,100 @@ dynamic_library_path = '/usr/local/lib/postgresql:$libdir'
       </listitem>
      </varlistentry>
 
-     <varlistentry id="guc-shared-memory-size" xreflabel="shared_memory_size">
-      <term><varname>shared_memory_size</varname> (<type>integer</type>)
+     <varlistentry id="guc-shared-memory-initial-size" xreflabel="shared_memory_initial_size">
+      <term><varname>shared_memory_initial_size</varname> (<type>integer</type>)
+      <indexterm>
+       <primary><varname>shared_memory_initial_size</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+       <para>
+        Reports the amount of memory, rounded up to the nearest megabyte, allocated at the server startup in main shared memory area.
+       </para>
+      </listitem>
+     </varlistentry>
+
+     <varlistentry id="guc-shared-memory-minimum-size" xreflabel="shared_memory_minimum_size">
+      <term><varname>shared_memory_minimum_size</varname> (<type>integer</type>)
+      <indexterm>
+       <primary><varname>shared_memory_minimum_size</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+       <para>
+        Reports the minimum amount of memory, rounded up to the nearest megabyte, required in the main shared memory area.
+      </para>
+      </listitem>
+     </varlistentry>
+
+     <varlistentry id="guc-shared-memory-maximum-size" xreflabel="shared_memory_maximum_size">
+      <term><varname>shared_memory_maximum_size</varname> (<type>integer</type>)
+      <indexterm>
+       <primary><varname>shared_memory_maximum_size</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+       <para>
+        Reports the maximum size of the main shared memory area, rounded up
+        to the nearest megabyte. This is the amount of address space that
+        must be reserved for the main shared memory area. This is also the maximum amount of memory that may be allocated in the main shared memory area.
+       </para>
+      </listitem>
+     </varlistentry>
+
+     <varlistentry id="guc-shared-memory-initial-size-in-huge-pages" xreflabel="shared_memory_initial_size_in_huge_pages">
+      <term><varname>shared_memory_initial_size_in_huge_pages</varname> (<type>integer</type>)
       <indexterm>
-       <primary><varname>shared_memory_size</varname> configuration parameter</primary>
+       <primary><varname>shared_memory_initial_size_in_huge_pages</varname> configuration parameter</primary>
       </indexterm>
       </term>
       <listitem>
        <para>
-        Reports the size of the main shared memory area, rounded up to the
-        nearest megabyte.
+        Reports the number of huge pages needed in the main shared memory area
+        at the startup based on the specified <xref
+        linkend="guc-huge-page-size"/>. If huge pages are not supported, this
+        will be <literal>-1</literal>.
+       </para>
+       <para>
+        This setting is supported only on <productname>Linux</productname>. It
+        is always set to <literal>-1</literal> on other platforms. For more
+        details about using huge pages on <productname>Linux</productname>, see
+        <xref linkend="linux-huge-pages"/>.
        </para>
       </listitem>
      </varlistentry>
 
-     <varlistentry id="guc-shared-memory-size-in-huge-pages" xreflabel="shared_memory_size_in_huge_pages">
-      <term><varname>shared_memory_size_in_huge_pages</varname> (<type>integer</type>)
+     <varlistentry id="guc-shared-memory-minimum-size-in-huge-pages" xreflabel="shared_memory_minimum_size_in_huge_pages">
+      <term><varname>shared_memory_minimum_size_in_huge_pages</varname> (<type>integer</type>)
       <indexterm>
-       <primary><varname>shared_memory_size_in_huge_pages</varname> configuration parameter</primary>
+       <primary><varname>shared_memory_minimum_size_in_huge_pages</varname> configuration parameter</primary>
       </indexterm>
       </term>
       <listitem>
        <para>
-        Reports the number of huge pages that are needed for the main shared
-        memory area based on the specified <xref linkend="guc-huge-page-size"/>.
+        Reports the minimum number of huge pages needed in the main shared memory area based on the specified <xref linkend="guc-huge-page-size"/>.
         If huge pages are not supported, this will be <literal>-1</literal>.
        </para>
+       <para>
+        This setting is supported only on <productname>Linux</productname>.  It
+        is always set to <literal>-1</literal> on other platforms.
+       </para>
+      </listitem>
+     </varlistentry>
+
+     <varlistentry id="guc-shared-memory-maximum-size-in-huge-pages" xreflabel="shared_memory_maximum_size_in_huge_pages">
+      <term><varname>shared_memory_maximum_size_in_huge_pages</varname> (<type>integer</type>)
+      <indexterm>
+       <primary><varname>shared_memory_maximum_size_in_huge_pages</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+       <para>
+        Reports the maximum number of huge pages needed in the
+        main shared memory area based on the specified
+        <xref linkend="guc-huge-page-size"/>. If huge pages are not
+        supported, this will be <literal>-1</literal>.
+       </para>
        <para>
         This setting is supported only on <productname>Linux</productname>.  It
         is always set to <literal>-1</literal> on other platforms.  For more
diff --git a/doc/src/sgml/ref/postgres-ref.sgml b/doc/src/sgml/ref/postgres-ref.sgml
index b13a16a117f..3eefd629e06 100644
--- a/doc/src/sgml/ref/postgres-ref.sgml
+++ b/doc/src/sgml/ref/postgres-ref.sgml
@@ -143,8 +143,12 @@ PostgreSQL documentation
        <para>
         This can be used on a running server for most parameters.  However,
         the server must be shut down for some runtime-computed parameters
-        (e.g., <xref linkend="guc-shared-memory-size"/>,
-        <xref linkend="guc-shared-memory-size-in-huge-pages"/>, and
+        (e.g., <xref linkend="guc-shared-memory-initial-size"/>,
+        <xref linkend="guc-shared-memory-minimum-size"/>,
+        <xref linkend="guc-shared-memory-maximum-size"/>,
+        <xref linkend="guc-shared-memory-initial-size-in-huge-pages"/>,
+        <xref linkend="guc-shared-memory-minimum-size-in-huge-pages"/>,
+        <xref linkend="guc-shared-memory-maximum-size-in-huge-pages"/>, and
         <xref linkend="guc-wal-segment-size"/>).
        </para>
 
diff --git a/doc/src/sgml/runtime.sgml b/doc/src/sgml/runtime.sgml
index daa87bfaa64..3762ae69702 100644
--- a/doc/src/sgml/runtime.sgml
+++ b/doc/src/sgml/runtime.sgml
@@ -1452,11 +1452,12 @@ export PG_OOM_ADJUST_VALUE=0
     <varname>CONFIG_HUGETLB_PAGE=y</varname>. You will also have to configure
     the operating system to provide enough huge pages of the desired size.
     The runtime-computed parameter
-    <xref linkend="guc-shared-memory-size-in-huge-pages"/> reports the number
-    of huge pages required.  This parameter can be viewed before starting the
+    <xref linkend="guc-shared-memory-maximum-size-in-huge-pages"/> reports the
+    number of huge pages that must be available in the pool for postmaster
+    startup to succeed.  This parameter can be viewed before starting the
     server with a <command>postgres</command> command like:
 <programlisting>
-$ <userinput>postgres -D $PGDATA -C shared_memory_size_in_huge_pages</userinput>
+$ <userinput>postgres -D $PGDATA -C shared_memory_maximum_size_in_huge_pages</userinput>
 3170
 $ <userinput>grep ^Hugepagesize /proc/meminfo</userinput>
 Hugepagesize:       2048 kB
@@ -1467,7 +1468,7 @@ hugepages-1048576kB  hugepages-2048kB
      In this example the default is 2MB, but you can also explicitly request
      either 2MB or 1GB with <xref linkend="guc-huge-page-size"/> to adapt
      the number of pages calculated by
-     <varname>shared_memory_size_in_huge_pages</varname>.
+     <varname>shared_memory_maximum_size_in_huge_pages</varname>.
 
      While we need at least <literal>3170</literal> huge pages in this example,
      a larger setting would be appropriate if other programs on the machine
diff --git a/doc/src/sgml/system-views.sgml b/doc/src/sgml/system-views.sgml
index 77202e2c765..a9cadd7365f 100644
--- a/doc/src/sgml/system-views.sgml
+++ b/doc/src/sgml/system-views.sgml
@@ -4244,8 +4244,46 @@ SELECT * FROM pg_locks pl LEFT JOIN pg_prepared_xacts ppx
        Size of the allocation in bytes including padding. For anonymous
        allocations, no information about padding is available, so the
        <literal>size</literal> and <literal>allocated_size</literal> columns
-       will always be equal. Padding is not meaningful for free memory, so
-       the columns will be equal in that case also.
+       will always be equal. Padding is not meaningful for free memory, so the
+       columns will be equal in that case also. For resizable allocations which
+       may span multiple memory pages, the padding includes the padding due to
+       page alignment.
+      </para></entry>
+     </row>
+
+     <row>
+      <entry role="catalog_table_entry"><para role="column_definition">
+       <structfield>minimum_size</structfield> <type>int8</type>
+      </para>
+      <para>
+       Minimum size in bytes that the resizable allocation can shrink to. Equals
+       <structfield>size</structfield> for fixed-size allocations, anonymous
+       allocations, and free memory.
+      </para></entry>
+     </row>
+
+     <row>
+      <entry role="catalog_table_entry"><para role="column_definition">
+       <structfield>maximum_size</structfield> <type>int8</type>
+      </para>
+      <para>
+       Maximum size in bytes that the resizable allocation can grow to. Equals
+       <structfield>size</structfield> for fixed-size allocations, anonymous
+       allocations, and free memory.
+      </para></entry>
+     </row>
+
+     <row>
+      <entry role="catalog_table_entry"><para role="column_definition">
+       <structfield>reserved_space</structfield> <type>int8</type>
+      </para>
+      <para>
+       Address space reserved for the allocation in bytes. For resizable
+       structures, this is the total address space reserved to accommodate
+       growth up to <structfield>maximum_size</structfield>, and is greater
+       than or equal to <structfield>allocated_size</structfield>. For
+       fixed-size allocations, anonymous allocations, and free memory this
+       is same as <structfield>allocated_size</structfield>.
       </para></entry>
      </row>
     </tbody>
@@ -4259,6 +4297,21 @@ SELECT * FROM pg_locks pl LEFT JOIN pg_prepared_xacts ppx
    <literal>ShmemRequestHash()</literal>.
   </para>
 
+  <para>
+   Resizable structures are allocations whose size can change while the server
+   is running. <xref linkend="guc-have-resizable-shmem"/> indicates whether the
+   running server supports resizable allocations. Each such allocation has a
+   minimum size give by <structfield>minimum_size</structfield> it can shrink to
+   and a maximum size given by <structfield>maximum_size</structfield> it can
+   grow to; enough address space is reserved up front to accommodate its
+   <structfield>maximum_size</structfield>.  The aggregate initial, minimum and
+   maximum sizes of all shared memory allocations are reported by <xref
+   linkend="guc-shared-memory-initial-size"/>, <xref
+   linkend="guc-shared-memory-minimum-size"/> and <xref
+   linkend="guc-shared-memory-maximum-size"/> respectively (and their
+   <literal>_in_huge_pages</literal> counterparts).
+  </para>
+
   <para>
    By default, the <structname>pg_shmem_allocations</structname> view can be
    read only by superusers or roles with privileges of the
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index bc04d9dfc13..66d1bcd9055 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3715,6 +3715,99 @@ my_shmem_init(void *arg)
      </para>
     </sect3>
 
+    <sect3 id="xfunc-shared-addin-resizable">
+     <title>Resizable shared memory structures</title>
+
+     <para>
+     A resizable memory structure can be requested using
+     <function>ShmemRequestStruct</function> by passing
+     <parameter>.maximum_size</parameter> along with
+     <parameter>.size</parameter>. <parameter>.maximum_size</parameter> is
+     maximum size upto which the structure can grow where as
+     <parameter>.size</parameter> is the initial size of the structure.
+     Optionally, <parameter>.minimum_size</parameter> can be set to the minimum
+     size that the structure can shrink to. A request with all three sizes
+     equal is converted into a fixed-size structure request. While
+     contiguous address space worth <parameter>maximum_size</parameter> is
+     allocated to the structure, only memory worth <parameter>size</parameter>
+     bytes is allocated initially. The <function>init_fn</function> should only
+     initialize the <parameter>size</parameter> amount of memory. The actual
+     memory allocated to this structure at any point in time is given by <link
+     linkend="view-pg-shmem-allocations"><structname>pg_shmem_allocations</structname>.<structfield>allocated_size</structfield></link>
+     and the address space reserved for this structure is given by <link
+     linkend="view-pg-shmem-allocations"><structname>pg_shmem_allocations</structname>.<structfield>reserved_space</structfield></link>.
+     </para>
+
+    <para>
+    The structure can be resized using <function>ShmemResizeStruct</function> by
+    passing it the structure's name and the
+    new size which can be anywhere between <parameter>minimum_size</parameter>
+    and <parameter>maximum_size</parameter>. If the new size is smaller than the
+    current size of the structure, the memory between the new size and current
+    size is freed while keeping the contents of the memory upto new size intact.
+    If the new size is greater than the current size, memory is allocated upto
+    new size while keeping the current contents of the structure intact. The
+    starting address of the structure does not change because of resizing
+    operation.
+    </para>
+
+    <para>
+    <function>ShmemResizeStruct</function> returns <literal>true</literal> on
+    success. If the operating system cannot supply the additional memory
+    required to expand the structure, it emits a <literal>WARNING</literal>
+    naming the structure and the number of bytes that could not be allocated,
+    leaves the structure at its previous size, and returns
+    <literal>false</literal>.
+    </para>
+
+    <para>
+    <function>ShmemResizeStruct</function> does not coordinate with other
+    backends that may be accessing the shared structure. The caller is
+    responsible for ensuring that no backend is accessing the parts of the
+    structure between old size and the new size while
+    <function>ShmemResizeStruct</function> is executing. Similarly after the
+    function has finished, the caller must ensure that each backend knows the
+    new size before accessing the parts of the structure between the old size
+    and the new size. Accessing the range <literal>[current_size,
+    maximum_size)</literal> results in an undefined operating-system dependent
+    behaviour.
+    </para>
+
+    <para>
+    <function>ShmemProtectStruct</function> can be used to make the range beyond
+    the current size inaccessible in a backend's address space, so that stray
+    accesses cause a fault instead of silently succeeding. When a backend
+    starts, protections for all resizable structures are adjusted according to
+    their current sizes, so subsystems need not call
+    <function>ShmemProtectStruct</function> from their per-backend
+    initialization routines. During runtime after calling
+    <function>ShmemResizeStruct</function> from one backend,
+    <function>ShmemProtectStruct</function> should be called from all the
+    backends that may access the structure.
+    </para>
+
+    <para>
+    <productname>PostgreSQL</productname>'s
+    <function>ProcSignalBarrier</function> mechanism (see
+    <filename>src/include/storage/procsignal.h</filename>) may be used to
+    coordinate the resize across backends and adjusting access to the address
+    space.
+    </para>
+
+    <para>
+    This functionality is available only on the platforms which provide the APIs
+    necessary to reserve contiguous address space and to allocate or free memory
+    in that address space on demand. Macro <symbol>HAVE_RESIZABLE_SHMEM</symbol>
+    is defined on such platforms. It can be used to guard code related to
+    resizing a shared memory structure. The functionality is available on with
+    mmap'ed memory, so subsystems which use resizable structures may have to
+    addtionally disable resizable memory usage when <symbol>shared_memory_type</symbol> is not
+    <symbol>SHMEM_TYPE_MMAP</symbol>. A GUC <xref linkend="guc-have-resizable-shmem"/> is set to
+    <literal>on</literal> when this functionality is available in a running
+    server, <literal>off</literal> otherwise.
+    </para>
+    </sect3>
+
     <sect3 id="xfunc-shared-addin-after-startup">
      <title>Requesting Shared Memory after Startup with <function>ShmemRequestStruct</function></title>
 
@@ -3726,6 +3819,7 @@ my_shmem_init(void *arg)
       However, after startup the allocation can fail if there is not enough
       shared memory available. The system reserves some memory for allocations
       after startup, but that reservation is small.
+      Only fixed-size structures can be created after startup.
      </para>
      <para>
       By default, <function>RegisterShmemCallbacks()</function> fails with an
@@ -3747,13 +3841,16 @@ my_shmem_init(void *arg)
      </para>
      <para>
       A backend attaching to an already allocated shared memory area must
-      normally pass the same <literal>size</literal> that was used to allocate
-      it to <function>ShmemRequestStruct()</function>; a mismatch results in
-      an error.  If the attaching backend does not know the size in advance,
-      it can pass <literal>SHMEM_ATTACH_UNKNOWN_SIZE</literal> instead, to
-      skip this cross-check.  <literal>SHMEM_ATTACH_UNKNOWN_SIZE</literal> can
-      only be used to attach to an area that already exists; using it before
-      allocating the area results in an error.
+      normally pass the same sizes, <literal>size</literal>,
+      <literal>minimum_size</literal>, and <literal>maximum_size</literal>, to
+      <function>ShmemRequestStruct()</function> that were used to allocate it ;
+      a mismatch results in an error. If the caller
+      does not know the sizes and relies on some other process having already
+      created the structure, it can set <literal>size</literal> to
+      <literal>SHMEM_ATTACH_UNKNOWN_SIZE</literal> instead; sizes in the
+      <function>ShmemRequestStruct()</function> are then not used, and it is an
+      error if the structure does not already exist. This value cannot be used
+      during startup.
      </para>
     </sect3>
 
diff --git a/meson.build b/meson.build
index 3238c849e1b..a28205d278b 100644
--- a/meson.build
+++ b/meson.build
@@ -2903,6 +2903,23 @@ decl_checks = [
   ['timingsafe_bcmp',  'string.h'],
 ]
 
+# mmap and madvise constants needed for resizable shared memory.
+# Usually we use AC_CHECK_DECLS to check for function declarations, but in this
+# case we are using it to detect existence of constants. These constants are
+# used to define HAVE_RESIZABLE_SHMEM which is used in storage/pg_shmem.h as
+# well as storage/shmem.h. The first abstracts the APIs to allocate shared
+# memory segments from the operating system whereas the second abstracts APIs to
+# allocate shared memory to various subsystems. Since they are related but
+# orthogonal to each other, including any one of them in the other file doesn't
+# make sense. pg_config_manual.h is the only place where HAVE_RESIZABLE_SHMEM
+# can be defined and made available to both without including sys/mman.h. But
+# for that we need constants that indicate the existence of following defines.
+decl_checks += [
+  ['MAP_NORESERVE', 'sys/mman.h'],
+  ['MADV_POPULATE_WRITE', 'sys/mman.h'],
+  ['MADV_REMOVE', 'sys/mman.h'],
+]
+
 # Need to check for function declarations for these functions, because
 # checking for library symbols wouldn't handle deployment target
 # restrictions on macOS
diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index 80353c41af3..d3e3c9f90a1 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -245,7 +245,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 	char	   *userDoption = NULL;
 	uint32		bootstrap_data_checksum_version = PG_DATA_CHECKSUM_OFF;
 	yyscan_t	scanner;
-	Size		shmem_size;
+	List	   *subsegments;
 
 	Assert(!IsUnderPostmaster);
 
@@ -380,8 +380,10 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
 	InitializeFastPathLocks();
 
 	ShmemCallRequestCallbacks();
-	shmem_size = CalculateShmemSize();
-	CreateSharedMemoryAndSemaphores(shmem_size);
+	subsegments = PlanShmemLayout();
+	CreateSharedMemoryAndSemaphores(subsegments);
+	list_free_deep(subsegments);
+	subsegments = NIL;
 
 	/*
 	 * Estimate number of openable files.  This is essential too in --check
diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index 0605e6e3772..533ad2a961d 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -37,6 +37,7 @@
 #include "storage/shmem.h"
 #include "utils/guc.h"
 #include "utils/guc_hooks.h"
+#include "utils/injection_point.h"
 #include "utils/pidfile.h"
 
 
@@ -104,6 +105,8 @@ static void IpcMemoryDelete(int status, Datum shmId);
 static IpcMemoryState PGSharedMemoryAttach(IpcMemoryId shmId,
 										   void *attachAt,
 										   PGShmemHeader **addr);
+static void *TryAnonymousSegment(List *subsegments, Size *size, Size page_size,
+								 int flags);
 
 
 /*
@@ -589,46 +592,83 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
 	return true;
 }
 
+/*
+ * Get the page size being used by the shared memory.
+ *
+ * The function should be called only after the shared memory has been setup.
+ */
+size_t
+GetOSPageSize(void)
+{
+	size_t		os_page_size;
+
+	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
+
+	os_page_size = sysconf(_SC_PAGESIZE);
+
+	/* If huge pages are actually in use, use huge page size */
+	if (huge_pages_status == HUGE_PAGES_ON)
+		GetHugePageSize(&os_page_size, NULL);
+
+	return os_page_size;
+}
+
 /*
  * Creates an anonymous mmap()ed shared memory segment.
  *
- * Pass the requested size in *size.  This function will modify *size to the
- * actual size of the allocation, if it ends up allocating a segment that is
- * larger than requested.  The memory page size used is returned in *page_size.
+ * ... with the given subsegment allocated one after the other in that segment.
+ *
+ * The function allocates address space large enough to cover all the
+ * subsegments. Each subsegment gets address space worth its maximum size.
+ * Memory pages covering the initial size of each subsegment against its address
+ * space. The address space between the initial end of the segment and the
+ * maximal end of the segment remains reserved but not populated. Since these
+ * ends need not be page aligned, we round them to page boundaries as needed.
+ * This means that memory after the initial end upto the immediate page boundary
+ * will be allocated.  Also the memory page containing the maximal end of the
+ * structure will be allocated for the next subsegment.
+ *
+ * The function first tries to allocate the segment using huge pages if
+ * requested, and falls back to ordinary pages if that fails. It uses the
+ * TryAnonymousSegment() helper function to create anonymous segments and
+ * allocate memory pages according to the given memory layout in both cases.
+ *
+ * The size of the memory segment is returned through the 'size'.  The memory
+ * page size used is returned in `page_size`.
  */
 static void *
-CreateAnonymousSegment(Size *size, Size *page_size)
+CreateAnonymousSegment(List *subsegments, Size *size, Size *page_size)
 {
-	Size		allocsize = *size;
+	Size		allocsize;
 	void	   *ptr = MAP_FAILED;
 	int			mmap_errno = 0;
 	int			mmap_flags = MAP_SHARED | MAP_ANONYMOUS | MAP_HASSEMAPHORE;
 
+#ifdef HAVE_RESIZABLE_SHMEM
+	if (list_length(subsegments) > 1)
+		mmap_flags |= MAP_NORESERVE;
+#else
+	if (list_length(subsegments) > 1)
+		elog(FATAL, "resizable shared memory is not supported on this platform");
+#endif
+
 #ifndef MAP_HUGETLB
 	/* PGSharedMemoryCreate should have dealt with this case */
 	Assert(huge_pages != HUGE_PAGES_ON);
 #else
 	if (huge_pages == HUGE_PAGES_ON || huge_pages == HUGE_PAGES_TRY)
 	{
-		/*
-		 * Round up the request size to a suitable large value.
-		 */
 		Size		hugepagesize;
 		int			huge_mmap_flags;
 
 		GetHugePageSize(&hugepagesize, &huge_mmap_flags);
-
-		if (allocsize % hugepagesize != 0)
-			allocsize = add_size(allocsize, hugepagesize - (allocsize % hugepagesize));
-
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   mmap_flags | huge_mmap_flags, -1, 0);
+		ptr = TryAnonymousSegment(subsegments, &allocsize, hugepagesize,
+								  mmap_flags | huge_mmap_flags);
 		mmap_errno = errno;
 		if (ptr != MAP_FAILED)
 			*page_size = hugepagesize;
 		if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
-			elog(DEBUG1, "mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
-				 allocsize);
+			elog(DEBUG1, "could not allocate huge-page shared memory, falling back to ordinary pages: %m");
 	}
 #endif
 
@@ -642,22 +682,16 @@ CreateAnonymousSegment(Size *size, Size *page_size)
 
 	if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
 	{
-		/*
-		 * Use the original size, not the rounded-up value, when falling back
-		 * to non-huge pages.
-		 */
-		allocsize = *size;
-		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
-				   mmap_flags, -1, 0);
-		mmap_errno = errno;
 		*page_size = sysconf(_SC_PAGESIZE);
+		ptr = TryAnonymousSegment(subsegments, &allocsize, *page_size, mmap_flags);
+		mmap_errno = errno;
 	}
 
 	if (ptr == MAP_FAILED)
 	{
 		errno = mmap_errno;
 		ereport(FATAL,
-				(errmsg("could not map anonymous shared memory: %m"),
+				(errmsg("could not create anonymous shared memory segment: %m"),
 				 (mmap_errno == ENOMEM) ?
 				 errhint("This error usually means that PostgreSQL's request "
 						 "for a shared memory segment exceeded available memory, "
@@ -672,6 +706,225 @@ CreateAnonymousSegment(Size *size, Size *page_size)
 	return ptr;
 }
 
+/*
+ * Returns pointer to the anonymous shared memory segment when it successfully
+ * maps the address space and allocates the memory covering the initial
+ * requirement against each subsegment. MAP_FAILED otherwise.
+ *
+ * `flags` is used to map the memory segment and `page_size` is used to allocate
+ * memory pages against the mapped segment.  The function does not verify the
+ * consistency between these two parameters.
+ *
+ * In case the memory allocation fails against any of the subsegments, the
+ * successful allocations for previous subsegments are released.
+ *
+ * PGSharedMemoryProcessLayout() performs the actual memory allocation for the
+ * subsegments.
+ */
+static void *
+TryAnonymousSegment(List *subsegments, Size *size, Size page_size, int flags)
+{
+	void	   *ptr;
+#ifdef HAVE_RESIZABLE_SHMEM
+	Size		initial_size;
+	Size		minimum_size;
+#endif
+
+	/*
+	 * The address space to be reserved spans till the maximum end of the last
+	 * subsegment.
+	 */
+	*size = ((PGShmemSubsegment *) llast(subsegments))->maximum_end;
+
+	/*
+	 * Round up to the nearest page boundary since the memory will be
+	 * allocated in pages anyway.
+	 */
+	if (*size % page_size != 0)
+		*size = add_size(*size, page_size - (*size % page_size));
+
+	ptr = mmap(NULL, *size, PROT_READ | PROT_WRITE, flags, -1, 0);
+	if (ptr == MAP_FAILED)
+		return MAP_FAILED;
+
+#ifdef HAVE_RESIZABLE_SHMEM
+
+	/*
+	 * If we are not using MAP_NORESERVE, memory is reserved by mmap() itself
+	 * nothing more to do.
+	 */
+	if ((flags & MAP_NORESERVE) == 0)
+	{
+		/*
+		 * When there are more than one subsegment, we should be using
+		 * MAP_NORESERVE lest we allocate more memory than necessary
+		 * initially.
+		 */
+		Assert(list_length(subsegments) == 1);
+		return ptr;
+	}
+
+	if (!PGSharedMemoryProcessLayout(subsegments, page_size, ptr,
+									 &initial_size, &minimum_size))
+	{
+		int			save_errno = errno;
+
+		/* Also releases pages populated before a partial allocation failure. */
+		if (munmap(ptr, *size) != 0)
+			elog(FATAL, "could not unmap failed shared memory allocation: %m");
+		errno = save_errno;
+		return MAP_FAILED;
+	}
+#endif
+
+	return ptr;
+}
+
+/*
+ * Given the memory layout specified by the subsegments, apply the layout in the
+ * address space starting at the given address. When address is NULL, only
+ * calculate the required memory sizes.
+ *
+ * Returns false on a system-call failure, leaving errno set.  The caller must
+ * unmap the segment to release any partial allocation.  The output sizes are
+ * only set on success.  With address == NULL, no system calls are performed.
+ */
+bool
+PGSharedMemoryProcessLayout(List *subsegments, Size page_size, void *address,
+							Size *initial, Size *minimum)
+{
+#ifdef HAVE_RESIZABLE_SHMEM
+	Size		initial_allocated_end = 0;
+	Size		minimum_allocated_end = 0;
+	Size		initial_size = 0;
+	Size		minimum_size = 0;
+#endif
+
+	Assert(page_size > 0);
+
+	/* NULL address is always page-aligned. */
+	Assert(address == (void *) TYPEALIGN(page_size, address));
+
+	/*
+	 * On the platforms which do not support resizable shared memory this
+	 * function will be called only to calculate the required amount of
+	 * memory. We don't expect multiple subsegments as well as a mapped
+	 * address in those cases, and the single subsegment must be fixed-size.
+	 */
+#define RETURN_FIXED_SHMEM_LAYOUT() \
+	do { \
+		PGShmemSubsegment *segment; \
+		Size		size; \
+		\
+		Assert(address == NULL && list_length(subsegments) == 1); \
+		segment = linitial(subsegments); \
+		Assert(segment->start == 0); \
+		Assert(segment->minimum_end == segment->initial_end && \
+			   segment->maximum_end == segment->initial_end); \
+		size = segment->initial_end; \
+		if (size % page_size != 0) \
+			size = add_size(size, page_size - (size % page_size)); \
+		*initial = *minimum = size; \
+		return true; \
+	} while (0)
+
+	/* We do not support resizable shared memory for SysV segments. */
+	if (shared_memory_type == SHMEM_TYPE_SYSV)
+		RETURN_FIXED_SHMEM_LAYOUT();
+
+#ifndef HAVE_RESIZABLE_SHMEM
+	RETURN_FIXED_SHMEM_LAYOUT();
+#else
+
+	/*
+	 * For every subsegment, calculate the boundaries of the memory hole
+	 * towards the end of the segment. Since we allocate memory in pages,
+	 * round up the initial and minimum ends to the nearest page boundary. If
+	 * a subsegment has its maximal end in the middle of a page, that page
+	 * will be allocated because of the next subsegment. Consider all these
+	 * paddings when calculating the initial and minimum memory requirements.
+	 */
+	foreach_ptr(PGShmemSubsegment, segment, subsegments)
+	{
+		Size		maximum_end = segment->maximum_end;
+		Size		initial_end = TYPEALIGN(page_size, segment->initial_end);
+		Size		minimum_end = TYPEALIGN(page_size, segment->minimum_end);
+		Size		hole_end = TYPEALIGN_DOWN(page_size, maximum_end);
+		Size		segment_end = maximum_end;
+
+		Assert(segment->start <= segment->minimum_end);
+		Assert(segment->minimum_end <= segment->initial_end);
+		Assert(segment->initial_end <= segment->maximum_end);
+
+		/*
+		 * Allocate memory for the initial portion of the subsegment, if not
+		 * already allocated.
+		 */
+		if (initial_end > initial_allocated_end)
+		{
+			if (address != NULL &&
+				madvise((char *) address + initial_allocated_end,
+						initial_end - initial_allocated_end,
+						MADV_POPULATE_WRITE) != 0)
+				return false;
+			initial_size = add_size(initial_size,
+									initial_end - initial_allocated_end);
+		}
+		if (minimum_end > minimum_allocated_end)
+			minimum_size = add_size(minimum_size,
+									minimum_end - minimum_allocated_end);
+
+		/*
+		 * Render the unused part ofthe subsegment as inaccessible. If the
+		 * maximum end of the subsegment is not page-aligned, the page where
+		 * it lands will be shared by the next subsegment. In that case leave
+		 * that page accessible.
+		 */
+		if (address != NULL && initial_end < hole_end &&
+			mprotect((char *) address + initial_end, hole_end - initial_end,
+					 PROT_NONE) != 0)
+			return false;
+
+		initial_allocated_end = Max(initial_end, hole_end);
+		minimum_allocated_end = Max(minimum_end, hole_end);
+
+		/*
+		 * Align the end of the segment to the nearest page boundary, if
+		 * required. Adjust the sizes to consider the padding upto the maximal
+		 * end.
+		 */
+		if (segment_end % page_size != 0)
+			segment_end = add_size(segment_end,
+								   page_size - (segment_end % page_size));
+
+		/* Retain the possibly shared page at an unaligned maximum end. */
+		if (segment_end > initial_allocated_end)
+		{
+			if (address != NULL)
+			{
+				Assert(segment_end - initial_allocated_end == page_size);
+				if (madvise((char *) address + initial_allocated_end,
+							segment_end - initial_allocated_end,
+							MADV_POPULATE_WRITE) != 0)
+					return false;
+			}
+			initial_size = add_size(initial_size,
+									segment_end - initial_allocated_end);
+		}
+		if (segment_end > minimum_allocated_end)
+			minimum_size = add_size(minimum_size,
+									segment_end - minimum_allocated_end);
+
+		initial_allocated_end = segment_end;
+		minimum_allocated_end = segment_end;
+	}
+	*initial = initial_size;
+	*minimum = minimum_size;
+	return true;
+#endif
+#undef RETURN_FIXED_SHMEM_LAYOUT
+}
+
 /*
  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
  * (called as an on_shmem_exit callback, hence funny argument list)
@@ -692,9 +945,12 @@ AnonymousShmemDetach(int status, Datum arg)
 /*
  * PGSharedMemoryCreate
  *
- * Create a shared memory segment of the given size and initialize its
- * standard header.  Also, register an on_shmem_exit callback to release
- * the storage.
+ * Create a shared memory segment with the given subsegment layout and
+ * initialize its standard header.  Also, register an on_shmem_exit callback to
+ * release the storage.
+ *
+ * Anonymous shared memory mappings may host multiple resizable subsegments.
+ * Other mappings have a single fixed-size subsegment.
  *
  * Dead Postgres segments pertinent to this DataDir are recycled if found, but
  * we do not fail upon collision with foreign shmem segments.  The idea here
@@ -702,8 +958,7 @@ AnonymousShmemDetach(int status, Datum arg)
  * postmaster or backend.
  */
 PGShmemHeader *
-PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+PGSharedMemoryCreate(List *subsegments, PGShmemHeader **shim)
 {
 	IpcMemoryKey NextShmemSegID;
 	void	   *memAddress;
@@ -711,6 +966,7 @@ PGSharedMemoryCreate(Size size,
 	struct stat statbuf;
 	Size		sysvsize;
 	Size		page_size;
+	Size		size;
 
 	/*
 	 * We use the data directory's ID info (inode and device numbers) to
@@ -737,12 +993,9 @@ PGSharedMemoryCreate(Size size,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("huge pages not supported with the current \"shared_memory_type\" setting")));
 
-	/* Room for a header? */
-	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
-
 	if (shared_memory_type == SHMEM_TYPE_MMAP)
 	{
-		AnonymousShmem = CreateAnonymousSegment(&size, &page_size);
+		AnonymousShmem = CreateAnonymousSegment(subsegments, &size, &page_size);
 		AnonymousShmemSize = size;
 
 		/* Register on-exit routine to unmap the anonymous segment */
@@ -753,14 +1006,35 @@ PGSharedMemoryCreate(Size size,
 	}
 	else
 	{
-		sysvsize = size;
+		PGShmemSubsegment *subsegment;
+
+		/*
+		 * We do not support resizable shared memory segments when SysV memory
+		 * is used. Hence there should be only one subsegment.
+		 */
+		Assert(list_length(subsegments) == 1);
+		subsegment = linitial(subsegments);
+
+		Assert(subsegment->start == 0);
+		Assert(subsegment->initial_end == subsegment->maximum_end &&
+			   subsegment->minimum_end == subsegment->maximum_end);
+
+		size = subsegment->initial_end;
+		sysvsize = subsegment->initial_end;
 		page_size = sysconf(_SC_PAGESIZE);
 
 		/* huge pages are only available with mmap */
 		SetConfigOption("huge_pages_status", "off",
 						PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+
+		/* resizable shared memory is only available with mmap */
+		SetConfigOption("have_resizable_shmem", "off",
+						PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
 	}
 
+	/* Room for a header? */
+	Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
+
 	/*
 	 * Loop till we find a free IPC key.  Trust CreateDataDirLockFile() to
 	 * ensure no more than one postmaster per data directory can enter this
@@ -997,3 +1271,183 @@ PGSharedMemoryDetach(void)
 		AnonymousShmem = NULL;
 	}
 }
+
+/*
+ * Make sure that the memory of given size from the given address is released.
+ *
+ * The address and size are expected to be page aligned.
+ *
+ * Only supported on platforms that support anonymous shared memory.
+ *
+ * On success returns true. false if system call fails.
+ */
+bool
+PGSharedMemoryEnsureFreed(void *addr, Size size)
+{
+#ifndef HAVE_RESIZABLE_SHMEM
+	ereport(ERROR,
+			errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			errmsg("resizable shared memory is not supported on this platform"));
+#else
+	if (!AnonymousShmem)
+		ereport(ERROR,
+				errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				errmsg("only anonymous shared memory can be freed"));
+
+#ifdef USE_ASSERT_CHECKING
+	{
+		size_t		os_page_size = GetOSPageSize();
+
+		Assert(addr == (void *) TYPEALIGN(os_page_size, addr));
+		Assert(size == TYPEALIGN(os_page_size, size));
+	}
+#endif
+
+	if (madvise(addr, size, MADV_REMOVE) == -1)
+	{
+		ereport(WARNING, errmsg("could not free shared memory: %m"));
+		return false;
+	}
+
+	return true;
+#endif
+}
+
+/*
+ * Make sure that the memory pages worth the given size are allocated at the
+ * given address.
+ *
+ * The address and size are expected to be page aligned.  The caller is
+ * responsible for ensuring that the range is already writable; this function
+ * only populates it.
+ *
+ * Only supported on platforms that support anonymous shared memory.
+ *
+ * Returns true on success, false otherwise. Any partial allocation is rolled
+ * back.
+ */
+bool
+PGSharedMemoryEnsureAllocated(void *addr, Size size)
+{
+#ifndef HAVE_RESIZABLE_SHMEM
+	ereport(ERROR,
+			errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			errmsg("resizable shared memory is not supported on this platform"));
+#else
+	bool		simulate_failure = false;
+	bool		result = true;
+
+	if (!AnonymousShmem)
+		ereport(ERROR,
+				errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				errmsg("only anonymous shared memory can be allocated at runtime"));
+
+#ifdef USE_ASSERT_CHECKING
+	{
+		size_t		os_page_size = GetOSPageSize();
+
+		Assert(addr == (void *) TYPEALIGN(os_page_size, addr));
+		Assert(size == TYPEALIGN(os_page_size, size));
+	}
+#endif
+
+	if (madvise(addr, size, MADV_POPULATE_WRITE) == -1)
+	{
+		ereport(WARNING,
+				errmsg("could not allocate %zu bytes of shared memory at %p: %m",
+					   size, addr));
+		result = false;
+	}
+
+	/*
+	 * Simulate memory allocation failure.
+	 *
+	 * Loading a library could run _PG_init(), whose shared memory requests
+	 * could try to acquire ShmemIndexLock, which the caller might have
+	 * already held. This can lead to self-deadlock. Assume that the caller
+	 * has loaded the injection point and use cached one here.
+	 */
+	if (result)
+		INJECTION_POINT_CACHED("shmem-allocate", &simulate_failure);
+
+	if (simulate_failure)
+	{
+		ereport(WARNING,
+				errmsg("simulated shared memory allocation failure"));
+		result = false;
+	}
+
+	/* Failed population can leave some or all of the pages allocated. */
+	if (!result)
+	{
+		if (madvise(addr, size, MADV_REMOVE) == -1)
+			ereport(ERROR,
+					(errcode(ERRCODE_SYSTEM_ERROR),
+					 errmsg("could not release %zu bytes of shared memory at %p after failed allocation: %m",
+							size, addr)));
+	}
+
+	return result;
+#endif
+}
+
+/*
+ * Set memory protection on the given region of shared memory.
+ *
+ * Makes [rw_start, rw_end) readable and writable, and [rw_end, prot_end)
+ * inaccessible.
+ *
+ * All addresses are expected to be page aligned.
+ *
+ * Only supported on platforms that support resizable shared memory.
+ *
+ * On success returns true, false if system call fails.
+ */
+bool
+PGSharedMemoryProtect(void *rw_start, void *rw_end, void *prot_end)
+{
+#ifndef HAVE_RESIZABLE_SHMEM
+	ereport(ERROR,
+			errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			errmsg("resizable shared memory is not supported on this platform"));
+#else
+
+	if (!AnonymousShmem)
+		ereport(ERROR,
+				errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				errmsg("only anonymous shared memory can be protected at runtime"));
+
+#ifdef USE_ASSERT_CHECKING
+	{
+		size_t		os_page_size = GetOSPageSize();
+
+		Assert(rw_start == (void *) TYPEALIGN(os_page_size, rw_start));
+		Assert(rw_end == (void *) TYPEALIGN(os_page_size, rw_end));
+		Assert(prot_end == (void *) TYPEALIGN(os_page_size, prot_end));
+	}
+#endif
+	Assert(rw_end >= rw_start);
+
+	if (rw_end > rw_start)
+	{
+		if (mprotect(rw_start, (char *) rw_end - (char *) rw_start,
+					 PROT_READ | PROT_WRITE) != 0)
+		{
+			ereport(WARNING, errmsg("could not protect shared memory: %m"));
+			return false;
+		}
+	}
+
+	if (prot_end > rw_end)
+	{
+		if (mprotect(rw_end, (char *) prot_end - (char *) rw_end,
+					 PROT_NONE) != 0)
+		{
+			ereport(WARNING, errmsg("could not protect shared memory: %m"));
+			return false;
+		}
+	}
+
+	return true;
+#endif
+}
diff --git a/src/backend/port/win32_shmem.c b/src/backend/port/win32_shmem.c
index e842adce7e0..177fa81f6c4 100644
--- a/src/backend/port/win32_shmem.c
+++ b/src/backend/port/win32_shmem.c
@@ -197,16 +197,61 @@ EnableLockPagesPrivilege(int elevel)
 	return TRUE;
 }
 
+/*
+ * PGSharedMemoryProcessLayout
+ *
+ * Windows currently supports only a single fixed-size subsegment. Unlike Linux
+ * anonymous memory, this function does not apply given subsegment layouts to a
+ * mapped address; it returns the sizes of the single subsegment rounded to
+ * the page size.
+ *
+ * We need this function here so that the platform specific code does not bleed
+ * into shared memory size calculation in the common code while the memory layout
+ * application and memory calculation logics remain in sync on the platforms
+ * supporting resizable shared memory structures. In future, when we will support
+ * resizable shared memory on Windows, this function will be called from
+ * PGSharedMemoryCreate to apply the given layout for multiple subsegments.
+ */
+bool
+PGSharedMemoryProcessLayout(List *subsegments, Size page_size, void *address,
+							Size *initial, Size *minimum)
+{
+	PGShmemSubsegment *subsegment;
+	Size		size;
+
+	Assert(page_size > 0);
+
+	/* The function should not be called to apply memory layouts currently. */
+	Assert(address == NULL);
+	Assert(list_length(subsegments) == 1);
+
+	subsegment = linitial(subsegments);
+
+	/* A single fixed-size subsegment is expected */
+	Assert(subsegment->start == 0);
+	Assert(subsegment->minimum_end == subsegment->maximum_end &&
+		   subsegment->maximum_end == subsegment->initial_end);
+
+	size = subsegment->initial_end;
+	if (size % page_size != 0)
+		size = add_size(size, page_size - (size % page_size));
+
+	*initial = size;
+	*minimum = size;
+	return true;
+}
+
 /*
  * PGSharedMemoryCreate
  *
- * Create a shared memory segment of the given size and initialize its
- * standard header.
+ * Create a shared memory segment of the given size and initialize its standard
+ * header.
  */
 PGShmemHeader *
-PGSharedMemoryCreate(Size size,
-					 PGShmemHeader **shim)
+PGSharedMemoryCreate(List *subsegments, PGShmemHeader **shim)
 {
+	PGShmemSubsegment *subsegment;
+	Size		size;
 	void	   *memAddress;
 	PGShmemHeader *hdr;
 	HANDLE		hmap,
@@ -216,10 +261,27 @@ PGSharedMemoryCreate(Size size,
 	DWORD		size_high;
 	DWORD		size_low;
 	SIZE_T		largePageSize = 0;
-	Size		orig_size = size;
+	Size		orig_size;
 	DWORD		flProtect = PAGE_READWRITE;
 	DWORD		desiredAccess;
 
+	/*
+	 * On the platforms that support resizable shared memory, the shared
+	 * memory segment is required to be divided into multiple subsegments.
+	 * Windows does not support resizable shared memory, so there's only a
+	 * single undivided segment to be created.
+	 */
+	Assert(list_length(subsegments) == 1);
+
+	subsegment = linitial(subsegments);
+
+	Assert(subsegment->start == 0);
+	Assert(subsegment->minimum_end == subsegment->maximum_end &&
+		   subsegment->maximum_end == subsegment->initial_end);
+
+	size = subsegment->initial_end;
+	orig_size = size;
+
 	ShmemProtectiveRegion = VirtualAlloc(NULL, PROTECTIVE_REGION_SIZE,
 										 MEM_RESERVE, PAGE_NOACCESS);
 	if (ShmemProtectiveRegion == NULL)
@@ -657,3 +719,59 @@ check_huge_page_size(int *newval, void **extra, GucSource source)
 	}
 	return true;
 }
+
+/*
+ * Get the page size used by the shared memory.
+ *
+ * The function should be called only after the shared memory has been setup.
+ */
+size_t
+GetOSPageSize(void)
+{
+	SYSTEM_INFO sysinfo;
+	size_t		os_page_size;
+
+	Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
+
+	GetSystemInfo(&sysinfo);
+	os_page_size = sysinfo.dwPageSize;
+
+	/* If huge pages are actually in use, use huge page size */
+	if (huge_pages_status == HUGE_PAGES_ON)
+		GetHugePageSize(&os_page_size, NULL);
+
+	return os_page_size;
+}
+
+/*
+ * PGSharedMemoryEnsureFreed / PGSharedMemoryEnsureAllocated
+ *
+ * Not supported on Windows.  These are only meaningful on platforms with
+ * resizable shared memory (mmap + madvise).
+ */
+bool
+PGSharedMemoryEnsureFreed(void *addr, Size size)
+{
+	ereport(ERROR,
+			errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			errmsg("resizable shared memory is not supported on this platform"));
+	return false;				/* keep compiler quiet */
+}
+
+bool
+PGSharedMemoryEnsureAllocated(void *addr, Size size)
+{
+	ereport(ERROR,
+			errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			errmsg("resizable shared memory is not supported on this platform"));
+	return false;				/* keep compiler quiet */
+}
+
+bool
+PGSharedMemoryProtect(void *rw_start, void *rw_end, void *prot_end)
+{
+	ereport(ERROR,
+			errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			errmsg("resizable shared memory is not supported on this platform"));
+	return false;				/* keep compiler quiet */
+}
diff --git a/src/backend/postmaster/auxprocess.c b/src/backend/postmaster/auxprocess.c
index ad4bf4bd2a8..07a3b5c5923 100644
--- a/src/backend/postmaster/auxprocess.c
+++ b/src/backend/postmaster/auxprocess.c
@@ -69,33 +69,43 @@ AuxiliaryProcessMainCommon(void)
 	BaseInit();
 
 	/*
-	 * Prevent consuming interrupts between setting ProcSignalInit and setting
-	 * the initial local data checksum value.  If a barrier is emitted, and
-	 * absorbed, before local cached state is initialized the state transition
-	 * can be invalid.
-	 */
-	HOLD_INTERRUPTS();
-
-	ProcSignalInit(NULL, 0);
-
-	/*
-	 * Initialize a local cache of the data_checksum_version, to be updated by
-	 * the procsignal-based barriers.
+	 * Prevent consuming interrupts between ProcSignalInit() and the
+	 * initialization of local states that are kept in sync with shared memory
+	 * via procsignal-based barriers. If a barrier is emitted, and absorbed,
+	 * before local cached state is initialized the state transition can be
+	 * invalid.
 	 *
-	 * This intentionally happens after initializing the procsignal, otherwise
-	 * we might miss a state change. This means we can get a barrier for the
-	 * state we've just initialized - but it can happen only once.
+	 * These initializations intentionally happen after ProcSignalInit(),
+	 * otherwise we might miss a state change. This means we may also receive
+	 * a barrier for the state we've just initialized, but it can happen only
+	 * once.
 	 *
 	 * The postmaster (which is what gets forked into the new child process)
-	 * does not handle barriers, therefore it may not have the current value
-	 * of LocalDataChecksumState value (it'll have the value read from the
-	 * control file, which may be arbitrarily old).
+	 * does not handle barriers, therefore its local states may not reflect
+	 * the current state of the shared memory.
 	 *
 	 * NB: Even if the postmaster handled barriers, the value might still be
 	 * stale, as it might have changed after this process forked.
 	 */
+	HOLD_INTERRUPTS();
+
+	ProcSignalInit(NULL, 0);
+
+	/*
+	 * LocalDataChecksumState inherited from Postmaster will have the value
+	 * read from the control file, which may be arbitrarily old. Update it.
+	 */
 	InitLocalDataChecksumState();
 
+	/*
+	 * Refresh per-backend protections for resizable shmem structures, in case
+	 * these structures have been resized since the startup. Structures are
+	 * expected to be kept in sync by respective subsystems using
+	 * procsignal-based barriers. But we modify their protections en-masse
+	 * here, rather than relying on individual subsystems to do it.
+	 */
+	ShmemReprotectResizableStructs();
+
 	RESUME_INTERRUPTS();
 
 	/*
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 75a25bf0bde..8c0bd23630e 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -501,7 +501,7 @@ PostmasterMain(int argc, char *argv[])
 	char	   *userDoption = NULL;
 	bool		listen_addr_saved = false;
 	char	   *output_config_variable = NULL;
-	Size		shmem_size;
+	List	   *subsegments;
 
 	InitProcessGlobals();
 
@@ -974,14 +974,14 @@ PostmasterMain(int argc, char *argv[])
 	 * shared memory needs.
 	 */
 	ShmemCallRequestCallbacks();
-	shmem_size = CalculateShmemSize();
+	subsegments = PlanShmemLayout();
 
 	/*
 	 * Now that loadable modules have had their chance to request additional
 	 * shared memory, determine the value of any runtime-computed GUCs that
 	 * depend on the amount of shared memory required.
 	 */
-	InitializeShmemGUCs(shmem_size);
+	InitializeShmemGUCs(subsegments);
 
 	/*
 	 * Now that modules have been loaded, we can process any custom resource
@@ -1016,7 +1016,9 @@ PostmasterMain(int argc, char *argv[])
 	 * normally choose the same IPC keys.  This helps ensure that we will
 	 * clean up dead IPC objects if the postmaster crashes and is restarted.
 	 */
-	CreateSharedMemoryAndSemaphores(shmem_size);
+	CreateSharedMemoryAndSemaphores(subsegments);
+	list_free_deep(subsegments);
+	subsegments = NIL;
 
 	/*
 	 * Estimate number of openable files.  This must happen after setting up
@@ -3260,7 +3262,7 @@ PostmasterStateMachine(void)
 	 */
 	if (FatalError && pmState == PM_NO_CHILDREN)
 	{
-		Size		shmem_size;
+		List	   *subsegments;
 
 		ereport(LOG,
 				(errmsg("all server processes terminated; reinitializing")));
@@ -3285,8 +3287,10 @@ PostmasterStateMachine(void)
 		 */
 		ResetShmemAllocator();
 		ShmemCallRequestCallbacks();
-		shmem_size = CalculateShmemSize();
-		CreateSharedMemoryAndSemaphores(shmem_size);
+		subsegments = PlanShmemLayout();
+		CreateSharedMemoryAndSemaphores(subsegments);
+		list_free_deep(subsegments);
+		subsegments = NIL;
 
 		UpdatePMState(PM_STARTUP);
 
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 51e6a9a801c..99a23ab982b 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -50,37 +50,57 @@ RequestAddinShmemSpace(Size size)
 }
 
 /*
- * CalculateShmemSize
- *		Calculates the amount of shared memory needed.
+ * PlanShmemLayout
+ *		Plan shared memory layout.
  *
  * Expected to be called only once after collecting all shared memory requests
  * but before allocating the shared memory segment at the startup or server
  * restart.
+ *
+ * It uses ShmemPlanRequestedLayout() to arrange the shared memory requests into
+ * subsegments and adds the final subsegment for any additional memory not
+ * covered by the requests.
+ *
+ * We take some care to ensure that the total size request doesn't overflow
+ * size_t.  If this gets through, we don't need to be so careful during the
+ * actual allocation phase.
+ *
+ * The returned list may be freed after the requested structures have been
+ * initialized.
  */
-Size
-CalculateShmemSize(void)
+List *
+PlanShmemLayout(void)
 {
-	Size		size;
+	List	   *subsegments = ShmemPlanRequestedLayout();
+	PGShmemSubsegment *last = llast(subsegments);
+	size_t		fixed_addins;
 
 	/*
 	 * Size of the Postgres shared-memory block is estimated via moderately-
 	 * accurate estimates for the big hogs, plus 100K for the stuff that's too
 	 * small to bother with estimating.
 	 *
-	 * We take some care to ensure that the total size request doesn't
-	 * overflow size_t.  If this gets through, we don't need to be so careful
-	 * during the actual allocation phase.
+	 * Also include additional requested shmem from preload libraries.
+	 *
+	 * Create a new subsegment for the additional memory if the last
+	 * subsegment is resizable; we need every resizable structure to end the
+	 * subsegment that contains it.
 	 */
-	size = 100000;
-	size = add_size(size, ShmemGetRequestedSize());
-
-	/* include additional requested shmem from preload libraries */
-	size = add_size(size, total_addin_request);
+	if (last->maximum_end != last->minimum_end)
+	{
+		Size		start = last->maximum_end;
 
-	/* might as well round it off to a multiple of a typical page size */
-	size = add_size(size, 8192 - (size % 8192));
+		last = palloc0(sizeof(PGShmemSubsegment));
+		last->start = start;
+		last->minimum_end = last->initial_end = last->maximum_end = start;
+		subsegments = lappend(subsegments, last);
+	}
 
-	return size;
+	fixed_addins = add_size(100000, total_addin_request);
+	last->initial_end = add_size(last->initial_end, fixed_addins);
+	last->minimum_end = add_size(last->minimum_end, fixed_addins);
+	last->maximum_end = add_size(last->maximum_end, fixed_addins);
+	return subsegments;
 }
 
 #ifdef EXEC_BACKEND
@@ -118,22 +138,35 @@ AttachSharedMemoryStructs(void)
 
 /*
  * CreateSharedMemoryAndSemaphores
- *		Creates and initializes shared memory of given size and semaphores.
+ *		Creates and initializes shared memory and semaphores.
+ *
+ * The shared memory is laid out in subsegments specified in the input list.
  */
 void
-CreateSharedMemoryAndSemaphores(Size size)
+CreateSharedMemoryAndSemaphores(List *subsegments)
 {
 	PGShmemHeader *shim;
 	PGShmemHeader *seghdr;
+	int			subsegment_no = 0;
 
 	Assert(!IsUnderPostmaster);
 
-	elog(DEBUG3, "invoking IpcMemoryCreate(size=%zu)", size);
+	foreach_ptr(PGShmemSubsegment, segment, subsegments)
+	{
+		elog(DEBUG3, "shared memory subsegment %d: initial size=%zu, minimum size=%zu, maximum size=%zu",
+			 subsegment_no, segment->initial_end - segment->start,
+			 segment->minimum_end - segment->start,
+			 segment->maximum_end - segment->start);
+		subsegment_no++;
+	}
 
 	/*
-	 * Create the shmem segment
+	 * Create the shmem segment.
+	 *
+	 * Reserve enough shared address space to accommodate every requested
+	 * structure grown to its maximum size.
 	 */
-	seghdr = PGSharedMemoryCreate(size, &shim);
+	seghdr = PGSharedMemoryCreate(subsegments, &shim);
 
 	/*
 	 * Make sure that huge pages are never reported as "unknown" while the
@@ -158,6 +191,14 @@ CreateSharedMemoryAndSemaphores(Size size)
 	 */
 	if (shmem_startup_hook)
 		shmem_startup_hook();
+
+	/*
+	 * Make the resizable shared memory structures inaccessible in the
+	 * postmaster. Do this after initializing shared memory. See
+	 * ShmemProtectResizableStructsInPM() for details.
+	 */
+	if (IsPostmasterEnvironment)
+		ShmemProtectResizableStructsInPM();
 }
 
 /*
@@ -184,36 +225,86 @@ RegisterBuiltinShmemCallbacks(void)
  * InitializeShmemGUCs
  *
  * This function initializes runtime-computed GUCs related to the amount of
- * shared memory required for the current configuration. The input size is expected to be the total shared memory size computed for the current configuration.
+ * shared memory required for the current configuration. The shared memory is
+ * planned to be laid out per given subsegments list and the layout is expected
+ * to be computed based on the current configuration.
  */
 void
-InitializeShmemGUCs(Size size_b)
+InitializeShmemGUCs(List *subsegments)
 {
 	char		buf[64];
-	Size		size_mb;
-	Size		hp_size;
+	size_t		initial_b;
+	size_t		min_b;
+	size_t		max_b;
+	size_t		hp_size;
+	size_t		size_mb;
+	Size		page_size;
+#ifdef WIN32
+	SYSTEM_INFO sysinfo;
+#else
+	long		os_page_size;
+#endif
+
+	max_b = ((PGShmemSubsegment *) llast(subsegments))->maximum_end;
 
 	/*
-	 * Round the shared memory size up to the nearest megabyte.
+	 * Compute the initial and minimum shared memory allocation requirements
+	 * using default page size.
 	 */
-	size_mb = add_size(size_b, (1024 * 1024) - 1) / (1024 * 1024);
+#ifdef WIN32
+	GetSystemInfo(&sysinfo);
+	page_size = sysinfo.dwPageSize;
+#else
+	os_page_size = sysconf(_SC_PAGESIZE);
+	if (os_page_size <= 0)
+		ereport(ERROR,
+				(errcode(ERRCODE_SYSTEM_ERROR),
+				 errmsg("could not determine system page size")));
+	page_size = os_page_size;
+#endif
+	PGSharedMemoryProcessLayout(subsegments, page_size, NULL, &initial_b, &min_b);
+
+	/* Round each size up to the nearest megabyte. */
+	size_mb = add_size(initial_b, (1024 * 1024) - 1) / (1024 * 1024);
+	sprintf(buf, "%zu", size_mb);
+	SetConfigOption("shared_memory_initial_size", buf,
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+
+	size_mb = add_size(min_b, (1024 * 1024) - 1) / (1024 * 1024);
+	sprintf(buf, "%zu", size_mb);
+	SetConfigOption("shared_memory_minimum_size", buf,
+					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+
+	size_mb = add_size(max_b, (1024 * 1024) - 1) / (1024 * 1024);
 	sprintf(buf, "%zu", size_mb);
-	SetConfigOption("shared_memory_size", buf,
+	SetConfigOption("shared_memory_maximum_size", buf,
 					PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
 
 	/*
-	 * Calculate the number of huge pages required.
+	 * Compute the initial and minimum shared memory allocation requirements
+	 * using huge page size.
 	 */
 	GetHugePageSize(&hp_size, NULL);
 	if (hp_size != 0)
 	{
-		Size		hp_required;
+		size_t		hp_required;
+
+		PGSharedMemoryProcessLayout(subsegments, hp_size, NULL,
+									&initial_b, &min_b);
+
+		hp_required = initial_b / hp_size + (initial_b % hp_size != 0);
+		sprintf(buf, "%zu", hp_required);
+		SetConfigOption("shared_memory_initial_size_in_huge_pages", buf,
+						PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
+
+		hp_required = min_b / hp_size + (min_b % hp_size != 0);
+		sprintf(buf, "%zu", hp_required);
+		SetConfigOption("shared_memory_minimum_size_in_huge_pages", buf,
+						PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
 
-		hp_required = size_b / hp_size;
-		if (size_b % hp_size != 0)
-			hp_required = add_size(hp_required, 1);
+		hp_required = max_b / hp_size + (max_b % hp_size != 0);
 		sprintf(buf, "%zu", hp_required);
-		SetConfigOption("shared_memory_size_in_huge_pages", buf,
+		SetConfigOption("shared_memory_maximum_size_in_huge_pages", buf,
 						PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
 	}
 
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index e0576e8bdba..25775bde79d 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -19,11 +19,11 @@
  * methods).  The routines in this file are used for allocating and
  * binding to shared memory data structures.
  *
- * This module provides facilities to allocate fixed-size structures in shared
- * memory, for things like variables shared between all backend processes.
- * Each such structure has a string name to identify it, specified when it is
- * requested.  shmem_hash.c provides a shared hash table implementation on top
- * of that.
+ * This module provides facilities to allocate fixed-size as well as resizable
+ * structures in shared memory, for things like variables shared between all
+ * backend processes. Each such structure has a string name to identify it,
+ * specified when it is requested.  shmem_hash.c provides a shared hash table
+ * implementation on top of fixed-size structures.
  *
  * Shared memory areas should usually not be allocated after postmaster
  * startup, although we do allow small allocations later for the benefit of
@@ -102,6 +102,26 @@
  * (*options->ptr), and calls the attach_fn callback, if any, for additional
  * per-backend setup.
  *
+ * Resizable shared memory structures
+ * ----------------------------------
+ *
+ * In order to allocate resizable shared memory structures, set
+ * ShmemRequestStructOpts::maximum_size to the maximum size that the structure
+ * can grow to.  The address space for the maximum size will be reserved at
+ * startup, but memory is allocated or freed as the structure grows or shrinks
+ * respectively. ShmemRequestStructOpts::size should be set to the initial size
+ * of the structure, which is the amount of memory allocated at the startup.
+ * Optionally, ShmemRequestStructOpts::minimum_size can be set to the minimum
+ * size that the structure can shrink to. After startup, the structure can be
+ * resized by calling ShmemResizeStruct(). ShmemResizeStruct() enforces that the
+ * new size is within [minimum_size, maximum_size]. Equal bounds are allowed,
+ * but describe a fixed-size structure that cannot be resized.
+ *
+ * Since the memory available for allocating shared structures after startup is
+ * limited, it does not make much sense to support creating resizable shared
+ * structures after startup. It can be changed later if we find a compelling use
+ * case.
+ *
  * Legacy ShmemInitStruct()/ShmemInitHash() functions
  * --------------------------------------------------
  *
@@ -128,6 +148,8 @@
 
 #include "postgres.h"
 
+#include "utils/injection_point.h"
+
 #include <unistd.h>
 
 #include "access/slru.h"
@@ -172,6 +194,20 @@ typedef struct
 
 	/* InitShmemIndexEntry() sets this pointer when the area is allocated */
 	ShmemIndexEnt *index_entry;
+
+#ifdef USE_ASSERT_CHECKING
+
+	/*
+	 * Used only for validating planned memory layout of shared memory
+	 * requests at the startup.
+	 */
+	PGShmemSubsegment *subsegment;	/* Memory subsegment this request is
+									 * planned to be allocated in. */
+	Size		planned_offset; /* Offset within the shared memory segment
+								 * where this request is planned to be
+								 * allocated. */
+#endif
+
 } ShmemRequest;
 
 static List *pending_shmem_requests;	/* List of ShmemRequests */
@@ -277,6 +313,10 @@ typedef struct ShmemIndexEnt
 	Size		size;			/* # bytes requested for the structure */
 	Size		allocated_size; /* # bytes actually allocated */
 	bool		initialized;	/* has the init callback been run? */
+	Size		minimum_size;	/* the minimum size the structure can shrink
+								 * to */
+	Size		maximum_size;	/* the maximum size the structure can grow to */
+	Size		reserved_space; /* the total address space reserved */
 } ShmemIndexEnt;
 
 /* To get reliable results for NUMA inquiry we need to "touch pages" once */
@@ -286,6 +326,7 @@ static void CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks);
 static void ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks);
 static void InitShmemIndexEntry(ShmemRequest *request);
 static bool AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok);
+static void ShmemProtectStructInternal(ShmemIndexEnt *entry);
 
 Datum		pg_numa_available(PG_FUNCTION_ARGS);
 
@@ -352,7 +393,7 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
 	if (shmem_request_state != SRS_REQUESTING)
 		elog(ERROR, "ShmemRequestStruct can only be called from a shmem_request callback");
 
-	/* Check the options */
+	/* Check the options: name */
 	if (options->name == NULL)
 		elog(ERROR, "shared memory request is missing 'name' option");
 
@@ -361,14 +402,73 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
 		if (ShmemIndex == NULL)
 			elog(ERROR, "SHMEM_ATTACH_UNKNOWN_SIZE cannot be used during startup");
 	}
-	else if (options->size <= 0)
-		elog(ERROR, "invalid size %zd for shared memory request for \"%s\"",
-			 options->size, options->name);
 
+	/* Check options: alignment */
 	if (options->alignment != 0 && pg_nextpower2_size_t(options->alignment) != options->alignment)
 		elog(ERROR, "invalid alignment %zu for shared memory request for \"%s\"",
 			 options->alignment, options->name);
 
+	/*
+	 * Check options: sizes, only if the request may end up creating a
+	 * structure.
+	 */
+	if (options->size != SHMEM_ATTACH_UNKNOWN_SIZE)
+	{
+		if (options->size <= 0)
+			elog(ERROR, "invalid size %zd for shared memory request for \"%s\"",
+				 options->size, options->name);
+		if (options->minimum_size < 0)
+			elog(ERROR, "invalid minimum_size %zd for shared memory request for \"%s\"",
+				 options->minimum_size, options->name);
+		if (options->maximum_size < 0)
+			elog(ERROR, "invalid maximum_size %zd for shared memory request for \"%s\"",
+				 options->maximum_size, options->name);
+
+#ifndef HAVE_RESIZABLE_SHMEM
+		if (options->maximum_size > 0 || options->minimum_size > 0)
+			elog(ERROR, "resizable shared memory is not supported on this platform");
+#else
+		if ((options->maximum_size > 0 || options->minimum_size > 0) &&
+			shared_memory_type != SHMEM_TYPE_MMAP)
+			elog(ERROR, "resizable shared memory requires shared_memory_type = mmap");
+#endif
+
+		/* For a resizable structure max >= size >= min. */
+		if (options->maximum_size > 0)
+		{
+			if (options->size > options->maximum_size)
+				elog(ERROR, "resizable shared memory structure \"%s\" should have size (%zd) less than or equal to maximum size (%zd)",
+					 options->name, options->size, options->maximum_size);
+			if (options->size < options->minimum_size)
+				elog(ERROR, "resizable shared memory structure \"%s\" should have size (%zd) greater than or equal to minimum size (%zd)",
+					 options->name, options->size, options->minimum_size);
+			if (options->minimum_size > options->maximum_size)
+				elog(ERROR, "resizable shared memory structure \"%s\" should have minimum size (%zd) less than or equal to maximum size (%zd)",
+					 options->name, options->minimum_size, options->maximum_size);
+
+			/*
+			 * A structure with equal minimum and maximum bounds is
+			 * practically a fixed-size allocation with no room to grow or
+			 * shrink. The shared memory index identifies fixed-size
+			 * structures by equal bounds, and the resize and protection
+			 * routines rely on that convention. Normalize the request so that
+			 * layout planning and allocation also treat it as fixed-size,
+			 * rather than introducing a separate category for resizable
+			 * structures with no permitted size change.
+			 */
+			if (options->minimum_size == options->maximum_size)
+			{
+				ereport(WARNING,
+						errmsg("shared memory structure \"%s\" has equal minimum and maximum sizes",
+							   options->name),
+						errdetail("The request will be treated as a fixed-size allocation of %zd bytes.",
+								  options->size));
+				options->minimum_size = 0;
+				options->maximum_size = 0;
+			}
+		}
+	}
+
 	/* Check that it's not already registered in this process */
 	foreach_ptr(ShmemRequest, existing, pending_shmem_requests)
 	{
@@ -383,44 +483,138 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
 	request = palloc_object(ShmemRequest);
 	request->options = options;
 	request->kind = kind;
+#ifdef USE_ASSERT_CHECKING
+	request->subsegment = NULL;
+	request->planned_offset = 0;
+#endif
 	request->index_entry = NULL;
 	pending_shmem_requests = lappend(pending_shmem_requests, request);
 	MemoryContextSwitchTo(oldcontext);
 }
 
 /*
- * ShmemGetRequestedSize() --- estimate the total size of all registered shared
- * memory structures.
+ * ShmemPlanRequestedLayout() --- lay out registered shared memory requests into
+ * subsegments.
+ *
+ * Arrange the shared memory requests into subsegments each ending at the only
+ * resizable structure in it except maybe the final subsegment which may not
+ * contain one. For each subsegment calculate its starting offset within the
+ * shared memory segment, its minimum end offset, maximum offset and the offset
+ * where the subsegment will end at the startup.
+ *
+ * Since the shared memory is allocated in pages, the actual amount of the memory
+ * allocated against a subsegment depends upon the page size, we do not attempt
+ * to calculate it precisely here when the page size to be used is not yet known.
  *
  * This is called at postmaster startup or server restart, before the shared
  * memory segment has been created.
+ *
+ *
+ * The returned list may be freed after the requested structures have been
+ * initialized.
  */
-size_t
-ShmemGetRequestedSize(void)
+List *
+ShmemPlanRequestedLayout(void)
 {
-	size_t		size;
+	List	   *subsegments = NIL;
+	PGShmemSubsegment *segment = palloc0(sizeof(PGShmemSubsegment));
+	Size		offset;
 
 	Assert(shmem_request_state == SRS_REQUESTING);
 
-	/* memory needed for the ShmemIndex */
-	size = hash_estimate_size(list_length(pending_shmem_requests) + SHMEM_INDEX_ADDITIONAL_SIZE,
-							  sizeof(ShmemIndexEnt));
-	size = CACHELINEALIGN(size);
+	/*
+	 * The header, allocator, and ShmemIndex precede the requested areas. This
+	 * needs to agree with the InitShmemAllocator()
+	 */
+	offset = CACHELINEALIGN(MAXALIGN(sizeof(PGShmemHeader)) +
+							sizeof(ShmemAllocatorData));
+	offset = add_size(offset,
+					  hash_estimate_size(list_length(pending_shmem_requests) +
+										 SHMEM_INDEX_ADDITIONAL_SIZE,
+										 sizeof(ShmemIndexEnt)));
+	segment->minimum_end = segment->initial_end = segment->maximum_end = offset;
 
 	/* memory needed for all the requested areas */
 	foreach_ptr(ShmemRequest, request, pending_shmem_requests)
 	{
-		size_t		alignment = request->options->alignment;
+		Size		alignment = request->options->alignment;
+		Size		req_min;
+		Size		req_max;
+		Size		req_initial = request->options->size;
+		Size		padding;
+
+		if (request->options->maximum_size > 0)
+		{
+			req_min = request->options->minimum_size;
+			req_max = request->options->maximum_size;
+		}
+		else
+		{
+			req_min = req_initial;
+			req_max = req_initial;
+		}
 
 		/* pad the start address for alignment like ShmemAllocRaw() does */
 		if (alignment < PG_CACHE_LINE_SIZE)
 			alignment = PG_CACHE_LINE_SIZE;
-		size = TYPEALIGN(alignment, size);
 
-		size = add_size(size, request->options->size);
+		/* Padding to align the start of the requested area */
+		padding = TYPEALIGN(alignment, offset) - offset;
+
+		offset = add_size(offset, padding);
+#ifdef USE_ASSERT_CHECKING
+
+		/*
+		 * Link every request to the subsegment where the requested structure
+		 * will reside. This reference is used later to validate that the
+		 * structure is allocated as planned.
+		 */
+		request->subsegment = segment;
+		request->planned_offset = offset;
+#endif
+
+		/*
+		 * Update the subsegment ends accounting for the padding for this
+		 * structure.  Padding affects all the sizes since it shifts the start
+		 * of the structure.
+		 */
+		segment->initial_end = add_size(offset, req_initial);
+		segment->minimum_end = add_size(offset, req_min);
+		segment->maximum_end = add_size(offset, req_max);
+		offset = segment->maximum_end;
+
+		/*
+		 * A resizable structure must be the last structure in the subsegment.
+		 * Validate the sizes and start a new subsegment.
+		 */
+		if (request->options->maximum_size > 0)
+		{
+			Assert(segment->minimum_end >= segment->start &&
+				   segment->initial_end > segment->start);
+			Assert(segment->maximum_end >= segment->initial_end);
+			Assert(segment->maximum_end >= segment->minimum_end);
+			subsegments = lappend(subsegments, segment);
+
+			segment = palloc0(sizeof(PGShmemSubsegment));
+			segment->start = offset;
+			segment->minimum_end = segment->initial_end =
+				segment->maximum_end = offset;
+		}
+		else
+		{
+			/* Totals of fixed-size structures should match exactly. */
+			Assert(segment->initial_end == segment->maximum_end &&
+				   segment->initial_end == segment->minimum_end);
+		}
 	}
 
-	return size;
+	/* Ignore the last subsegment if it does not contain any structures. */
+	if (segment->initial_end > segment->start)
+		return lappend(subsegments, segment);
+	else
+		pfree(segment);
+
+	return subsegments;
 }
 
 /*
@@ -444,6 +638,11 @@ ShmemInitRequested(void)
 	 */
 	foreach_ptr(ShmemRequest, request, pending_shmem_requests)
 	{
+		/*
+		 * These requests should know which memory subsegment they are going
+		 * into.
+		 */
+		Assert(request->subsegment != NULL);
 		InitShmemIndexEntry(request);
 	}
 
@@ -530,10 +729,19 @@ InitShmemIndexEntry(ShmemRequest *request)
 	ShmemIndexEnt *index_entry;
 	bool		found;
 	size_t		allocated_size;
+	size_t		requested_size;
 	void	   *structPtr;
 
 	/* Size must be known at this point. */
 	Assert(request->options->size != SHMEM_ATTACH_UNKNOWN_SIZE);
+	Assert(request->options->size > 0);
+
+	/*
+	 * Resizable shared memory areas cannot be created after the startup, see
+	 * the comment at the top of this file for details.
+	 */
+	Assert(request->options->maximum_size == 0 ||
+		   shmem_request_state == SRS_INITIALIZING);
 
 	/* look it up in the shmem index */
 	index_entry = (ShmemIndexEnt *)
@@ -550,10 +758,14 @@ InitShmemIndexEntry(ShmemRequest *request)
 	}
 
 	/*
-	 * We inserted the entry to the shared memory index.  Allocate requested
-	 * amount of shared memory for it, and initialize the index entry.
+	 * We inserted the entry to the shared memory index. Allocate requested
+	 * amount of address space in the shared memory segment for it, and do
+	 * basic initialization. Structures requested during startup already have
+	 * enough memory pages allocated to cover their initial sizes.
 	 */
-	structPtr = ShmemAllocRaw(request->options->size,
+	requested_size = request->options->maximum_size > 0 ?
+		request->options->maximum_size : request->options->size;
+	structPtr = ShmemAllocRaw(requested_size,
 							  request->options->alignment,
 							  &allocated_size);
 	if (structPtr == NULL)
@@ -562,20 +774,90 @@ InitShmemIndexEntry(ShmemRequest *request)
 		hash_search(ShmemIndex, name, HASH_REMOVE, NULL);
 		ereport(ERROR,
 				(errcode(ERRCODE_OUT_OF_MEMORY),
-				 errmsg("not enough shared memory for data structure"
+				 errmsg("not enough shared memory space for data structure"
 						" \"%s\" (%zd bytes requested)",
-						name, request->options->size)));
+						name, requested_size)));
 	}
+
+#ifdef USE_ASSERT_CHECKING
+
+	/*
+	 * Make sure that the shared structures requested at the startup ended up
+	 * being allocated as planned. Late requests and legacy ShmemInitStruct()
+	 * allocations have no planning phase, even when the latter are made
+	 * during startup.
+	 */
+	if (request->subsegment != NULL)
+	{
+		Assert(shmem_request_state == SRS_INITIALIZING);
+		Assert(structPtr == (char *) ShmemBase + request->planned_offset);
+		Assert(request->planned_offset >= request->subsegment->start);
+
+		/* A resizable structure must be the last structure in the subsegment. */
+		if (request->options->maximum_size > 0)
+		{
+			Assert(request->planned_offset + request->options->minimum_size ==
+				   request->subsegment->minimum_end);
+			Assert(request->planned_offset + request->options->size ==
+				   request->subsegment->initial_end);
+			Assert(request->planned_offset + requested_size ==
+				   request->subsegment->maximum_end);
+		}
+		else
+		{
+			Assert(request->planned_offset + request->options->size <=
+				   request->subsegment->initial_end);
+			Assert(request->planned_offset + requested_size <=
+				   request->subsegment->maximum_end);
+		}
+	}
+	else
+		Assert(request->planned_offset == 0);
+#endif
+
 	index_entry->size = request->options->size;
 	index_entry->allocated_size = allocated_size;
 	index_entry->location = structPtr;
+	index_entry->reserved_space = allocated_size;
+
+	/*
+	 * A failure in next steps may leave the entry without properly
+	 * initializing it. Mark it uninitialized for now.
+	 */
+	index_entry->initialized = false;
+	if (request->options->maximum_size > 0)
+	{
+		Size		page_size = pg_get_shmem_pagesize();
+		char	   *start;
+		char	   *end;
+
+		index_entry->minimum_size = request->options->minimum_size;
+		index_entry->maximum_size = request->options->maximum_size;
+
+		Assert(index_entry->maximum_size >= index_entry->size);
+		Assert(index_entry->reserved_space >= index_entry->maximum_size);
+
+		start = (char *) TYPEALIGN(page_size,
+								   (char *) structPtr + index_entry->size);
+		end = (char *) TYPEALIGN_DOWN(page_size,
+									  (char *) structPtr + index_entry->maximum_size);
+		start = Min(start, end);
+
+		/* Adjust the allocated size to exclude the unused memory pages. */
+		index_entry->allocated_size = index_entry->reserved_space - (end - start);
+	}
+	else
+	{
+		index_entry->minimum_size = request->options->size;
+		index_entry->maximum_size = request->options->size;
+	}
 
 	/*
 	 * The area is considered fully initialized only after the subsystem's
 	 * init callback has been called.  For now, perform only basic
-	 * initialization based on the kind of shmem area it is.
+	 * initialization based on the kind of shmem area it is and leave the
+	 * entry marked as uninitialized.
 	 */
-	index_entry->initialized = false;
 	switch (request->kind)
 	{
 		case SHMEM_KIND_STRUCT:
@@ -635,16 +917,50 @@ AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok)
 				(errmsg("cannot attach to shared memory struct \"%s\" because it was not fully initialized",
 						request->options->name)));
 
-	/* Check that the size in the index matches the request */
-	if (index_entry->size != request->options->size &&
-		request->options->size != SHMEM_ATTACH_UNKNOWN_SIZE)
+	/* Check sizes unless the caller requested attachment without size checks. */
+	if (request->options->size != SHMEM_ATTACH_UNKNOWN_SIZE)
 	{
-		ereport(ERROR,
-				(errmsg("shared memory struct \"%s\" was created with"
-						" different size: existing %zu, requested %zd",
-						name, index_entry->size, request->options->size)));
+		if (index_entry->size != request->options->size)
+		{
+			ereport(ERROR,
+					(errmsg("shared memory struct \"%s\" was created with"
+							" different size: existing %zu, requested %zd",
+							name, index_entry->size, request->options->size)));
+		}
+
+		/*
+		 * For resizable structures, also check that minimum_size and
+		 * maximum_size match. For fixed-size structures, these are derived
+		 * (set to size) in the index entry and not meaningful in the request.
+		 */
+		if (request->options->maximum_size > 0)
+		{
+			if (index_entry->minimum_size != request->options->minimum_size)
+			{
+				ereport(ERROR,
+						errmsg("shared memory struct \"%s\" was created with"
+							   " different minimum_size: existing %zu, requested %zd",
+							   name, index_entry->minimum_size,
+							   request->options->minimum_size));
+			}
+
+			if (index_entry->maximum_size != request->options->maximum_size)
+			{
+				ereport(ERROR,
+						errmsg("shared memory struct \"%s\" was created with"
+							   " different maximum_size: existing %zu, requested %zd",
+							   name, index_entry->maximum_size,
+							   request->options->maximum_size));
+			}
+		}
+		else if (index_entry->minimum_size != index_entry->maximum_size)
+			elog(ERROR, "shared memory struct \"%s\" was created as resizable, but requested as fixed-size",
+				 name);
 	}
 
+	if (index_entry->minimum_size != index_entry->maximum_size)
+		ShmemProtectStructInternal(index_entry);
+
 	/*
 	 * Re-establish the caller's pointer variable, or do other actions to
 	 * attach depending on the kind of shmem area it is.
@@ -668,6 +984,321 @@ AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok)
 	return true;
 }
 
+/*
+ * ShmemResizeStruct() --- resize a resizable shared memory structure.
+ *
+ * The new size must be within [minimum_size, maximum_size].  If the structure
+ * is being shrunk, the memory pages that are no longer needed are freed. If
+ * the structure is being expanded, the memory pages that are needed to cover the
+ * new size are allocated.
+ *
+ * The caller must ensure that no other backend is accessing the part of the
+ * structure between the old size and the new size while this function is
+ * running. It should also ensure that all backends that may access the
+ * structure have observed the new size before they access the range between
+ * the old size and the new size.
+ *
+ * If we can not allocate memory pages when expanding the structure, this
+ * function will return false. On success it returns true.
+ */
+bool
+ShmemResizeStruct(const char *name, Size new_size)
+{
+#ifndef HAVE_RESIZABLE_SHMEM
+	ereport(ERROR,
+			errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			errmsg("resizable shared memory is not supported on this platform"));
+	pg_unreachable();
+#else
+	ShmemIndexEnt *result;
+	bool		found;
+	Size		page_size = pg_get_shmem_pagesize();
+	char	   *new_end;
+	char	   *old_end;
+	char	   *reserved_end;
+	bool		success = true;
+
+	Assert(new_size > 0);
+
+	/*
+	 * Resizable shared memory structures are only supported with mmap'ed
+	 * memory.
+	 */
+	Assert(shared_memory_type == SHMEM_TYPE_MMAP);
+
+	/*
+	 * If INJECTION_POINT declaration leads to loading injection_point
+	 * library, it will allocate its shared memory structure taking
+	 * ShmemIndexLock. This can lead to a self deadlock. Load the injection
+	 * point before taking ShmemIndexLock, so that we can use the cached entry
+	 * later.
+	 */
+	INJECTION_POINT_LOAD("shmem-allocate");
+
+	/* look it up in the shmem index */
+	LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
+	result = (ShmemIndexEnt *) hash_search(ShmemIndex, name, HASH_FIND, &found);
+	if (!found)
+		ereport(ERROR,
+				errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				errmsg("shmem struct \"%s\" is not initialized", name));
+
+	Assert(result);
+
+	if (result->minimum_size == result->maximum_size)
+		ereport(ERROR,
+				errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				errmsg("shared memory struct \"%s\" is not resizable", name));
+
+	if (new_size < result->minimum_size)
+		ereport(ERROR,
+				errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+				errmsg("cannot shrink shared memory structure \"%s\" below minimum size"
+					   "(requested %zu bytes, minimum %zu bytes)",
+					   name, new_size, result->minimum_size));
+
+	if (result->maximum_size < new_size)
+		ereport(ERROR,
+				errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+				errmsg("not enough address space is reserved for resizing structure \"%s\""
+					   " (required %zu bytes, reserved %zu bytes)",
+					   name, new_size, result->maximum_size));
+
+	/*
+	 * Memory is allocated in pages. Calculate the new and old end addresses
+	 * of the structure aligned to page boundaries.  When expanding, we
+	 * allocate any memory pages between the old end and the new end.  When
+	 * shrinking, release memory pages beyond the new end, upto the old end.
+	 * If the maximal end of the structure is not page aligned, the page
+	 * containing maximal end of the structure always remains allocated as the
+	 * page will contain the next structure.
+	 */
+	new_end = (char *) TYPEALIGN(page_size, (char *) result->location + new_size);
+	old_end = (char *) TYPEALIGN(page_size, (char *) result->location + result->size);
+	reserved_end = (char *) TYPEALIGN_DOWN(page_size,
+										   (char *) result->location + result->maximum_size);
+	new_end = Min(new_end, reserved_end);
+	old_end = Min(old_end, reserved_end);
+	if (new_size < result->size)
+	{
+		if (old_end > new_end)
+		{
+			if (!PGSharedMemoryEnsureFreed(new_end, old_end - new_end))
+				ereport(ERROR,
+						errcode(ERRCODE_SYSTEM_ERROR),
+						errmsg("could not free %zu bytes of shared memory from structure \"%s\"",
+							   result->size - new_size, name));
+		}
+	}
+	else if (new_size > result->size)
+	{
+		if (new_end > old_end)
+		{
+			ShmemIndexEnt entry_copy = *result;
+
+			/*
+			 * Allocating memory pages in the expanded range may require the
+			 * corresponding address space to have read-write access.
+			 */
+			entry_copy.size = new_size;
+			ShmemProtectStructInternal(&entry_copy);
+
+			if (!PGSharedMemoryEnsureAllocated(old_end, new_end - old_end))
+			{
+				ShmemProtectStructInternal(result);
+				ereport(WARNING,
+						errcode(ERRCODE_OUT_OF_MEMORY),
+						errmsg("could not allocate %zu bytes of shared memory to structure \"%s\"",
+							   new_size - result->size, name));
+				success = false;
+			}
+		}
+	}
+
+	/* Update shmem index entry. */
+	if (success)
+	{
+		result->size = new_size;
+		Assert(result->maximum_size >= result->size);
+		Assert(result->reserved_space >= result->maximum_size);
+		result->allocated_size = result->reserved_space - (reserved_end - new_end);
+	}
+
+	LWLockRelease(ShmemIndexLock);
+
+	return success;
+#endif
+}
+
+/*
+ * ShmemProtectStruct() --- protect the unused portion of the given resizable
+ * structure.
+ *
+ * Makes the region beyond the current size up to maximum_size inaccessible, and
+ * ensures the region up to the current size is readable and writable. Depending
+ * upon the platform, the protection honours the page boundaries. So it may be
+ * more permissible than strictly needed.
+ *
+ * This function only affects the calling backend's address space. After each
+ * ShmemResizeStruct(), every backend that may access the structure should call
+ * this function before its next access. When backends are still in the middle
+ * of that round of ShmemProtectStruct() calls, ShmemResizeStruct() should not
+ * be called.
+ */
+void
+ShmemProtectStruct(const char *name)
+{
+#ifndef HAVE_RESIZABLE_SHMEM
+	ereport(ERROR,
+			errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			errmsg("resizable shared memory is not supported on this platform"));
+#else
+	ShmemIndexEnt *result;
+	bool		found;
+
+	LWLockAcquire(ShmemIndexLock, LW_SHARED);
+
+	result = (ShmemIndexEnt *) hash_search(ShmemIndex, name, HASH_FIND, &found);
+	if (!found)
+		ereport(ERROR,
+				errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				errmsg("shmem struct \"%s\" is not initialized", name));
+
+	if (result->minimum_size == result->maximum_size)
+		ereport(ERROR,
+				errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				errmsg("shared memory struct \"%s\" is not resizable", name));
+
+	ShmemProtectStructInternal(result);
+
+	LWLockRelease(ShmemIndexLock);
+#endif
+}
+
+/*
+ * ShmemProtectStructInternal --- same as ShmemProtectStruct()
+ *
+ * ..., but called when the ShmemIndexEnt of the struct is available. The caller
+ * should hold ShmemIndexLock if required.
+ */
+static void
+ShmemProtectStructInternal(ShmemIndexEnt *entry)
+{
+#ifndef HAVE_RESIZABLE_SHMEM
+	ereport(ERROR,
+			errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			errmsg("resizable shared memory is not supported on this platform"));
+#else
+	Size		page_size = pg_get_shmem_pagesize();
+	char	   *rw_start;
+	char	   *rw_end;
+	char	   *prot_end;
+
+	Assert(shared_memory_type == SHMEM_TYPE_MMAP);
+	Assert(entry->minimum_size != entry->maximum_size);
+
+	/* Make at least [location, location+size) readable and writable */
+	rw_start = (char *) TYPEALIGN_DOWN(page_size, entry->location);
+	rw_end = (char *) TYPEALIGN(page_size,
+								(char *) entry->location + entry->size);
+
+	/*
+	 * Make remaining portion inaccessible while making sure that the portion
+	 * after maximum_size is not affected since it may be used by other
+	 * structures.
+	 */
+	prot_end = (char *) TYPEALIGN_DOWN(page_size,
+									   (char *) entry->location + entry->maximum_size);
+
+	if (!PGSharedMemoryProtect(rw_start, rw_end, prot_end))
+		ereport(ERROR,
+				errcode(ERRCODE_SYSTEM_ERROR),
+				errmsg("could not protect shared memory structure \"%s\"", entry->key));
+#endif
+}
+
+/*
+ * ShmemProtectResizableStructsInPM() --- make resizable shared memory structures
+ * inaccessible to the postmaster.
+ *
+ * As the resizable structures undergo resizing the memory protection in the
+ * postmaster will become stale as there is no way for subsystems, especially the
+ * extensions, to update the protections in the postmaster. Forked backends will
+ * inherit the stale protection. Till they refresh it, they may gain access to
+ * the address space which may not have memory backing it.  Hence just make the
+ * resizable structures inaccessible to the Postmaster so that a backend
+ * accessing them without adjusting their protection to the current size would
+ * fault.
+ *
+ * XXX: This assumes that the postmaster will not attempt to access any
+ * resizable structures after this point. In case this assumption changes, we
+ * need to rethink the memory protection strategy for resizable structures in the
+ * postmaster.
+ */
+void
+ShmemProtectResizableStructsInPM(void)
+{
+#ifdef HAVE_RESIZABLE_SHMEM
+	HASH_SEQ_STATUS status;
+	ShmemIndexEnt *entry;
+
+	Assert(IsPostmasterEnvironment && !IsUnderPostmaster);
+
+	hash_seq_init(&status, ShmemIndex);
+	while ((entry = (ShmemIndexEnt *) hash_seq_search(&status)) != NULL)
+	{
+		/*
+		 * Use a copy with size set to 0 to apply postmaster protections
+		 * without changing the size recorded in the shared index.
+		 */
+		if (entry->minimum_size != entry->maximum_size)
+		{
+			ShmemIndexEnt entry_copy = *entry;
+
+			entry_copy.size = 0;
+			ShmemProtectStructInternal(&entry_copy);
+		}
+	}
+#endif
+}
+
+/*
+ * ShmemReprotectResizableStructs() --- re-apply protections to every
+ * resizable shmem structure at a backend startup.
+ *
+ * A new backend inherits protections from the postmaster. This is called early
+ * in backend startup to make the structures accessible according to their
+ * current sizes.
+ */
+void
+ShmemReprotectResizableStructs(void)
+{
+#ifdef HAVE_RESIZABLE_SHMEM
+	HASH_SEQ_STATUS status;
+	ShmemIndexEnt *entry;
+
+	/* Not intended for the postmaster itself. */
+	Assert(IsUnderPostmaster || !IsPostmasterEnvironment);
+
+	/*
+	 * In a standalone backend protections are applied when the shared memory
+	 * is created. It never inherits protections from the postmaster. Hence
+	 * reapplication is not needed.
+	 */
+	if (!IsUnderPostmaster)
+		return;
+
+	LWLockAcquire(ShmemIndexLock, LW_SHARED);
+	hash_seq_init(&status, ShmemIndex);
+	while ((entry = (ShmemIndexEnt *) hash_seq_search(&status)) != NULL)
+	{
+		if (entry->minimum_size != entry->maximum_size)
+			ShmemProtectStructInternal(entry);
+	}
+	LWLockRelease(ShmemIndexLock);
+#endif
+}
+
 /*
  *	InitShmemAllocator() --- set up basic pointers to shared memory.
  *
@@ -675,6 +1306,9 @@ AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok)
  * allocator's data structure in the shared memory segment.  In EXEC_BACKEND,
  * this is also called at backend startup, to set up pointers to the
  * already-initialized data structure.
+ *
+ * The memory layout here needs to agree with the memory layout expected by
+ * ShmemPlanRequestedLayout().
  */
 void
 InitShmemAllocator(PGShmemHeader *seghdr)
@@ -705,6 +1339,7 @@ InitShmemAllocator(PGShmemHeader *seghdr)
 	 */
 	Assert(seghdr == (void *) MAXALIGN(seghdr));
 	Assert(seghdr->content_offset == MAXALIGN(seghdr->content_offset));
+	Assert(seghdr->content_offset == MAXALIGN(sizeof(PGShmemHeader)));
 
 	/*
 	 * Allocations after this point should go through ShmemAlloc, which
@@ -774,6 +1409,9 @@ InitShmemAllocator(PGShmemHeader *seghdr)
 		Assert(!found);
 		result->size = ShmemAllocator->index_size;
 		result->allocated_size = ShmemAllocator->index_size;
+		result->minimum_size = result->size;
+		result->maximum_size = result->size;
+		result->reserved_space = result->allocated_size;
 		result->location = ShmemAllocator->index;
 		result->initialized = true;
 	}
@@ -1039,6 +1677,11 @@ ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks)
 						(errmsg("cannot attach to shared memory struct \"%s\" because it does not exist",
 								request->options->name),
 						 errdetail("SHMEM_ATTACH_UNKNOWN_SIZE can only be used to attach to an existing shared memory structure.")));
+			if (request->options->maximum_size > 0)
+				ereport(ERROR,
+						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+						 errmsg("cannot create resizable shared memory structure \"%s\" after startup",
+								request->options->name)));
 			notfound_any = true;
 		}
 	}
@@ -1150,7 +1793,7 @@ ShmemInitStruct(const char *name, Size size, bool *foundPtr)
 Datum
 pg_get_shmem_allocations(PG_FUNCTION_ARGS)
 {
-#define PG_GET_SHMEM_SIZES_COLS 4
+#define PG_GET_SHMEM_SIZES_COLS 7
 	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
 	HASH_SEQ_STATUS hstat;
 	ShmemIndexEnt *ent;
@@ -1172,7 +1815,20 @@ pg_get_shmem_allocations(PG_FUNCTION_ARGS)
 		values[1] = Int64GetDatum((char *) ent->location - (char *) ShmemSegHdr);
 		values[2] = Int64GetDatum(ent->size);
 		values[3] = Int64GetDatum(ent->allocated_size);
-		named_allocated += ent->allocated_size;
+		values[4] = Int64GetDatum(ent->minimum_size);
+		values[5] = Int64GetDatum(ent->maximum_size);
+		values[6] = Int64GetDatum(ent->reserved_space);
+
+		/*
+		 * Anonymous areas are allocated in the area remaining after all named
+		 * areas have been allocated. Thus the amount of shared memory
+		 * allocated for anonymous areas can be calculated as the total amount
+		 * of space allocated minus the amount of space allocated for named
+		 * areas. The amount of free shared memory at the end of the segment
+		 * can be calculated as the total size of the segment minus the total
+		 * amount of space allocated.
+		 */
+		named_allocated += ent->reserved_space;
 
 		tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
 							 values, nulls);
@@ -1183,6 +1839,9 @@ pg_get_shmem_allocations(PG_FUNCTION_ARGS)
 	nulls[1] = true;
 	values[2] = Int64GetDatum(ShmemAllocator->free_offset - named_allocated);
 	values[3] = values[2];
+	values[4] = values[2];
+	values[5] = values[2];
+	values[6] = values[2];
 	tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
 
 	/* output as-of-yet unused shared memory */
@@ -1191,6 +1850,9 @@ pg_get_shmem_allocations(PG_FUNCTION_ARGS)
 	nulls[1] = false;
 	values[2] = Int64GetDatum(ShmemSegHdr->totalsize - ShmemAllocator->free_offset);
 	values[3] = values[2];
+	values[4] = values[2];
+	values[5] = values[2];
+	values[6] = values[2];
 	tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
 
 	LWLockRelease(ShmemIndexLock);
diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c
index 82a1d4d2e26..e97aec3e333 100644
--- a/src/backend/storage/lmgr/lwlock.c
+++ b/src/backend/storage/lmgr/lwlock.c
@@ -423,7 +423,11 @@ LWLockShmemRequest(void *arg)
 					   .ptr = (void **) &LWLockTranches,
 		);
 
-	/* Space for the LWLock array */
+	/*
+	 * The size of the LWLock array is calculated only in the postmaster which
+	 * allocates the array. Other backends just attach to what the postmaster
+	 * already created.
+	 */
 	if (!IsUnderPostmaster)
 	{
 		num_main_array_locks = NUM_FIXED_LWLOCKS + NumLWLocksForNamedTranches();
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index a168bac3bc9..2950bc5248e 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -170,10 +170,16 @@ ProcGlobalShmemRequest(void *arg)
 					   .ptr = &AllProcsShmemPtr,
 		);
 
+	/*
+	 * The size of the Fast-Path Lock Array is calculated only in the
+	 * postmaster; other backends just attach to what the postmaster already
+	 * created.
+	 */
 	if (!IsUnderPostmaster)
 		size = FastPathLockArrayShmemSize = CalculateFastPathLockShmemSize();
 	else
 		size = SHMEM_ATTACH_UNKNOWN_SIZE;
+
 	ShmemRequestStruct(.name = "Fast-Path Lock Array",
 					   .size = size,
 					   .ptr = &FastPathLockArrayShmemPtr,
@@ -574,6 +580,14 @@ InitProcess(void)
 	if (IsUnderPostmaster)
 		AttachSharedMemoryStructs();
 #endif
+
+	/*
+	 * Update access to the address space occupied by the resizable shared
+	 * structures. We do it here so that the structures can be accessed safely
+	 * by this backend. But we will do this again after ProcSignalInit() for
+	 * the reasons mentioned there.
+	 */
+	ShmemReprotectResizableStructs();
 }
 
 /*
@@ -755,6 +769,14 @@ InitAuxiliaryProcess(void)
 	if (IsUnderPostmaster)
 		AttachSharedMemoryStructs();
 #endif
+
+	/*
+	 * Update access to the address space occupied by the resizable shared
+	 * structures. We do it here so that the structures can be accessed safely
+	 * by this backend. But we will do this again after ProcSignalInit() for
+	 * the reasons mentioned there.
+	 */
+	ShmemReprotectResizableStructs();
 }
 
 /*
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index b1c188daf22..0c82af868c1 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -4244,7 +4244,7 @@ PostgresSingleUserMain(int argc, char *argv[],
 					   const char *username)
 {
 	const char *dbname = NULL;
-	Size		shmem_size;
+	List	   *subsegments;
 
 	Assert(!IsUnderPostmaster);
 
@@ -4326,14 +4326,14 @@ PostgresSingleUserMain(int argc, char *argv[],
 	 * add-ins, a chance to chance to adjust their requested shmem sizes.
 	 */
 	ShmemCallRequestCallbacks();
-	shmem_size = CalculateShmemSize();
+	subsegments = PlanShmemLayout();
 
 	/*
 	 * Now that loadable modules have had their chance to request additional
 	 * shared memory, determine the value of any runtime-computed GUCs that
 	 * depend on the amount of shared memory required.
 	 */
-	InitializeShmemGUCs(shmem_size);
+	InitializeShmemGUCs(subsegments);
 
 	/*
 	 * Now that modules have been loaded, we can process any custom resource
@@ -4345,7 +4345,9 @@ PostgresSingleUserMain(int argc, char *argv[],
 	 * Create shared memory etc.  (Nothing's really "shared" in single-user
 	 * mode, but we must have these data structures anyway.)
 	 */
-	CreateSharedMemoryAndSemaphores(shmem_size);
+	CreateSharedMemoryAndSemaphores(subsegments);
+	list_free_deep(subsegments);
+	subsegments = NIL;
 
 	/*
 	 * Estimate number of openable files.  This must happen after setting up
diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c
index 8b6ea195eca..5219f43a687 100644
--- a/src/backend/utils/init/postinit.c
+++ b/src/backend/utils/init/postinit.c
@@ -788,6 +788,16 @@ InitPostgres(const char *in_dbname, Oid dboid,
 	 */
 	InitLocalDataChecksumState();
 
+	/*
+	 * Refresh per-backend protections for resizable shmem structures. Usually
+	 * the subsystems using resizable shared structures will use
+	 * ProcSignalBarrier mechanism to coordinate resizing which would involve
+	 * adjusting the protections as well. Like InitLocalDataChecksumState()
+	 * above, this must run after ProcSignalInit so as not to miss a barrier
+	 * for protection change.
+	 */
+	ShmemReprotectResizableStructs();
+
 	RESUME_INTERRUPTS();
 
 	/*
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index 8a8f1cca097..158b540962c 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -1234,6 +1234,13 @@
   max => '1000.0',
 },
 
+{ name => 'have_resizable_shmem', type => 'bool', context => 'PGC_INTERNAL', group => 'PRESET_OPTIONS',
+  short_desc => 'Shows whether the running server supports resizable shared memory.',
+  flags => 'GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE',
+  variable => 'have_resizable_shmem_enabled',
+  boot_val => 'HAVE_RESIZABLE_SHMEM_ENABLED',
+},
+
 { name => 'hba_file', type => 'string', context => 'PGC_POSTMASTER', group => 'FILE_LOCATIONS',
   short_desc => 'Sets the server\'s "hba" configuration file.',
   flags => 'GUC_SUPERUSER_ONLY',
@@ -2742,20 +2749,58 @@
   max => 'INT_MAX / 2',
 },
 
-{ name => 'shared_memory_size', type => 'int', context => 'PGC_INTERNAL', group => 'PRESET_OPTIONS',
-  short_desc => 'Shows the size of the server\'s main shared memory area (rounded up to the nearest MB).',
+{ name => 'shared_memory_initial_size', type => 'int', context => 'PGC_INTERNAL', group => 'PRESET_OPTIONS',
+  short_desc => 'Shows the amount of memory allocated at server startup in the main shared memory area (rounded up to the nearest MB).',
+  flags => 'GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_UNIT_MB | GUC_RUNTIME_COMPUTED',
+  variable => 'shared_memory_initial_size_mb',
+  boot_val => '0',
+  min => '0',
+  max => 'INT_MAX',
+},
+
+{ name => 'shared_memory_initial_size_in_huge_pages', type => 'int', context => 'PGC_INTERNAL', group => 'PRESET_OPTIONS',
+  short_desc => 'Shows the number of huge pages needed in the main shared memory area at server startup.',
+  long_desc => '-1 means huge pages are not supported.',
+  flags => 'GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_RUNTIME_COMPUTED',
+  variable => 'shared_memory_initial_size_in_huge_pages',
+  boot_val => '-1',
+  min => '-1',
+  max => 'INT_MAX',
+},
+
+{ name => 'shared_memory_maximum_size', type => 'int', context => 'PGC_INTERNAL', group => 'PRESET_OPTIONS',
+  short_desc => 'Shows the size of the main shared memory area and maximum memory that can be allocated in that area (rounded up to the nearest MB).',
+  flags => 'GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_UNIT_MB | GUC_RUNTIME_COMPUTED',
+  variable => 'shared_memory_maximum_size_mb',
+  boot_val => '0',
+  min => '0',
+  max => 'INT_MAX',
+},
+
+{ name => 'shared_memory_maximum_size_in_huge_pages', type => 'int', context => 'PGC_INTERNAL', group => 'PRESET_OPTIONS',
+  short_desc => 'Shows the maximum number of huge pages needed in the main shared memory area.',
+  long_desc => '-1 means huge pages are not supported.',
+  flags => 'GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_RUNTIME_COMPUTED',
+  variable => 'shared_memory_maximum_size_in_huge_pages',
+  boot_val => '-1',
+  min => '-1',
+  max => 'INT_MAX',
+},
+
+{ name => 'shared_memory_minimum_size', type => 'int', context => 'PGC_INTERNAL', group => 'PRESET_OPTIONS',
+  short_desc => 'Shows the minimum amount of memory required in the main shared memory area (rounded up to the nearest MB).',
   flags => 'GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_UNIT_MB | GUC_RUNTIME_COMPUTED',
-  variable => 'shared_memory_size_mb',
+  variable => 'shared_memory_minimum_size_mb',
   boot_val => '0',
   min => '0',
   max => 'INT_MAX',
 },
 
-{ name => 'shared_memory_size_in_huge_pages', type => 'int', context => 'PGC_INTERNAL', group => 'PRESET_OPTIONS',
-  short_desc => 'Shows the number of huge pages needed for the main shared memory area.',
+{ name => 'shared_memory_minimum_size_in_huge_pages', type => 'int', context => 'PGC_INTERNAL', group => 'PRESET_OPTIONS',
+  short_desc => 'Shows the minimum number of huge pages needed in the main shared memory area.',
   long_desc => '-1 means huge pages are not supported.',
   flags => 'GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_RUNTIME_COMPUTED',
-  variable => 'shared_memory_size_in_huge_pages',
+  variable => 'shared_memory_minimum_size_in_huge_pages',
   boot_val => '-1',
   min => '-1',
   max => 'INT_MAX',
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index a05fc356fc3..a7634ac0d80 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -652,8 +652,12 @@ static int	max_index_keys;
 static int	max_identifier_length;
 static int	block_size;
 static int	segment_size;
-static int	shared_memory_size_mb;
-static int	shared_memory_size_in_huge_pages;
+static int	shared_memory_initial_size_mb;
+static int	shared_memory_minimum_size_mb;
+static int	shared_memory_maximum_size_mb;
+static int	shared_memory_initial_size_in_huge_pages;
+static int	shared_memory_minimum_size_in_huge_pages;
+static int	shared_memory_maximum_size_in_huge_pages;
 static int	wal_block_size;
 static int	num_os_semaphores;
 static int	effective_wal_level = WAL_LEVEL_REPLICA;
@@ -673,6 +677,13 @@ static bool assert_enabled = DEFAULT_ASSERT_ENABLED;
 #endif
 static bool exec_backend_enabled = EXEC_BACKEND_ENABLED;
 
+#ifdef HAVE_RESIZABLE_SHMEM
+#define HAVE_RESIZABLE_SHMEM_ENABLED true
+#else
+#define HAVE_RESIZABLE_SHMEM_ENABLED false
+#endif
+static bool have_resizable_shmem_enabled = HAVE_RESIZABLE_SHMEM_ENABLED;
+
 static char *recovery_target_timeline_string;
 static char *recovery_target_string;
 static char *recovery_target_xid_string;
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 18b4be838a4..94e11a95c7d 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -8751,8 +8751,8 @@
 { oid => '5052', descr => 'allocations from the main shared memory segment',
   proname => 'pg_get_shmem_allocations', prorows => '50', proretset => 't',
   provolatile => 'v', prorettype => 'record', proargtypes => '',
-  proallargtypes => '{text,int8,int8,int8}', proargmodes => '{o,o,o,o}',
-  proargnames => '{name,off,size,allocated_size}',
+  proallargtypes => '{text,int8,int8,int8,int8,int8,int8}', proargmodes => '{o,o,o,o,o,o,o}',
+  proargnames => '{name,off,size,allocated_size,minimum_size,maximum_size,reserved_space}',
   prosrc => 'pg_get_shmem_allocations',
   proacl => '{POSTGRES=X,pg_read_all_stats=X}' },
 
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index 2e5ed6f5693..612c357b45e 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -85,6 +85,18 @@
    don't. */
 #undef HAVE_DECL_F_FULLFSYNC
 
+/* Define to 1 if you have the declaration of `MADV_POPULATE_WRITE', and to 0
+   if you don't. */
+#undef HAVE_DECL_MADV_POPULATE_WRITE
+
+/* Define to 1 if you have the declaration of `MADV_REMOVE', and to 0 if you
+   don't. */
+#undef HAVE_DECL_MADV_REMOVE
+
+/* Define to 1 if you have the declaration of `MAP_NORESERVE', and to 0 if you
+   don't. */
+#undef HAVE_DECL_MAP_NORESERVE
+
 /* Define to 1 if you have the declaration of `memset_s', and to 0 if you
    don't. */
 #undef HAVE_DECL_MEMSET_S
diff --git a/src/include/pg_config_manual.h b/src/include/pg_config_manual.h
index 521b49b8888..992fca9ae9e 100644
--- a/src/include/pg_config_manual.h
+++ b/src/include/pg_config_manual.h
@@ -131,6 +131,20 @@
 #define EXEC_BACKEND
 #endif
 
+/*
+ * HAVE_RESIZABLE_SHMEM indicates whether resizable shared memory structures are
+ * supported. The implementation requires MAP_NORESERVE, Linux-specific madvise
+ * constants (MADV_REMOVE and MADV_POPULATE_WRITE), and the mprotect() API.
+ *
+ * Resizable shared memory structures can be created only in anonymous memory
+ * segments which can not be used in EXEC_BACKEND mode. Hence they are not
+ * supported in EXEC_BACKEND mode as well.
+ */
+#if HAVE_DECL_MAP_NORESERVE && HAVE_DECL_MADV_REMOVE && \
+	HAVE_DECL_MADV_POPULATE_WRITE && !defined(EXEC_BACKEND)
+#define HAVE_RESIZABLE_SHMEM
+#endif
+
 /*
  * USE_POSIX_FADVISE controls whether Postgres will attempt to use the
  * posix_fadvise() kernel call.  Usually the automatic configure tests are
diff --git a/src/include/storage/ipc.h b/src/include/storage/ipc.h
index db5c69a08db..8efa49a55cd 100644
--- a/src/include/storage/ipc.h
+++ b/src/include/storage/ipc.h
@@ -18,6 +18,8 @@
 #ifndef IPC_H
 #define IPC_H
 
+#include "nodes/pg_list.h"
+
 typedef void (*pg_on_exit_callback) (int code, Datum arg);
 typedef void (*shmem_startup_hook_type) (void);
 
@@ -78,11 +80,11 @@ extern void check_on_shmem_exit_lists_are_empty(void);
 extern PGDLLIMPORT shmem_startup_hook_type shmem_startup_hook;
 
 extern void RegisterBuiltinShmemCallbacks(void);
-extern Size CalculateShmemSize(void);
-extern void CreateSharedMemoryAndSemaphores(Size size);
+extern List *PlanShmemLayout(void);
+extern void CreateSharedMemoryAndSemaphores(List *subsegments);
 #ifdef EXEC_BACKEND
 extern void AttachSharedMemoryStructs(void);
 #endif
-extern void InitializeShmemGUCs(Size size_b);
+extern void InitializeShmemGUCs(List *subsegments);
 
 #endif							/* IPC_H */
diff --git a/src/include/storage/pg_shmem.h b/src/include/storage/pg_shmem.h
index ef2c87a97de..f4b5e83fcdf 100644
--- a/src/include/storage/pg_shmem.h
+++ b/src/include/storage/pg_shmem.h
@@ -24,8 +24,37 @@
 #ifndef PG_SHMEM_H
 #define PG_SHMEM_H
 
+#include "nodes/pg_list.h"
 #include "storage/dsm_impl.h"
 
+/*
+ * Structure representing a subsegment of shared memory.
+ *
+ * When creating a shared memory segment, it is logically divided into
+ * subsegments. A subsegment hosts multiple fixed-size structures with an
+ * optional resizable structure at the end. They dictate the memory allocation
+ * against the address space of the shared memory segment during creation. They
+ * do not have any existence or meaning outside that process. All boundaries
+ * are byte offsets from the start of the shared memory segment, with exclusive
+ * ends, without any memory page alignment.
+ */
+typedef struct PGShmemSubsegment
+{
+	Size		start;
+
+	/*
+	 * For a subsegment containing no resizable structure, all the end offsets
+	 * are the same and correspond to the end of the last fixed sized
+	 * structure in that subsegment.
+	 */
+	Size		minimum_end;	/* offset where the minimal resizable
+								 * structure ends. */
+	Size		initial_end;	/* offset where the resizable structure ends
+								 * at startup. */
+	Size		maximum_end;	/* offset where the maximal resizable
+								 * structure ends. */
+}			PGShmemSubsegment;
+
 typedef struct PGShmemHeader	/* standard header for all Postgres shmem */
 {
 	int32		magic;			/* magic # to identify Postgres segments */
@@ -87,10 +116,16 @@ extern void PGSharedMemoryReAttach(void);
 extern void PGSharedMemoryNoReAttach(void);
 #endif
 
-extern PGShmemHeader *PGSharedMemoryCreate(Size size,
+extern PGShmemHeader *PGSharedMemoryCreate(List *subsegments,
 										   PGShmemHeader **shim);
+extern bool PGSharedMemoryProcessLayout(List *subsegments, Size page_size,
+										void *address, Size *initial, Size *minimum);
 extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
 extern void PGSharedMemoryDetach(void);
+extern bool PGSharedMemoryEnsureFreed(void *addr, Size size);
+extern bool PGSharedMemoryEnsureAllocated(void *addr, Size size);
+extern bool PGSharedMemoryProtect(void *rw_start, void *rw_end, void *prot_end);
 extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+extern size_t GetOSPageSize(void);
 
 #endif							/* PG_SHMEM_H */
diff --git a/src/include/storage/shmem.h b/src/include/storage/shmem.h
index 43b636868c7..389e4fe9e69 100644
--- a/src/include/storage/shmem.h
+++ b/src/include/storage/shmem.h
@@ -45,9 +45,9 @@ typedef struct ShmemStructOpts
 	/*
 	 * Requested size of the shmem allocation.
 	 *
-	 * When attaching to an existing allocation, the size must match the size
-	 * given when the shmem region was allocated.  This cross-check can be
-	 * disabled specifying SHMEM_ATTACH_UNKNOWN_SIZE.
+	 * When attaching, the supplied size and resizable bounds must match the
+	 * existing structure. Specify SHMEM_ATTACH_UNKNOWN_SIZE to attach without
+	 * checking any sizes; the structure must already exist.
 	 */
 	ssize_t		size;
 
@@ -57,6 +57,22 @@ typedef struct ShmemStructOpts
 	 */
 	size_t		alignment;
 
+	/*
+	 * Minimum size this structure can shrink to. Should be set to 0 for
+	 * fixed-size structures. Ignored when size is SHMEM_ATTACH_UNKNOWN_SIZE.
+	 */
+	ssize_t		minimum_size;
+
+	/*
+	 * Maximum size this structure can grow upto in future. The memory is not
+	 * allocated right away but the corresponding address space is reserved so
+	 * that memory can be mapped to it when the structure grows. Typically
+	 * should be used for large resizable structures which need several pages
+	 * worth of contiguous memory. Should be set to 0 for fixed-size
+	 * structures. Ignored when size is SHMEM_ATTACH_UNKNOWN_SIZE.
+	 */
+	ssize_t		maximum_size;
+
 	/*
 	 * When the shmem area is initialized or attached to, pointer to it is
 	 * stored in *ptr.  It usually points to a global variable, used to access
@@ -163,11 +179,16 @@ typedef struct ShmemCallbacks
  * this flag is set, it is allowed and the callbacks are called immediately to
  * initialize or attach to the requested shared memory areas.  This is not
  * used by any built-in subsystems, but extensions may find it useful.
+ * Resizable structures can only be attached to, not created, after startup.
  */
 #define SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP		0x00000001
 
 extern void RegisterShmemCallbacks(const ShmemCallbacks *callbacks);
 extern bool ShmemAddrIsValid(const void *addr);
+extern bool ShmemResizeStruct(const char *name, Size new_size);
+extern void ShmemProtectStruct(const char *name);
+extern void ShmemProtectResizableStructsInPM(void);
+extern void ShmemReprotectResizableStructs(void);
 
 /*
  * These macros provide syntactic sugar for calling the underlying functions
diff --git a/src/include/storage/shmem_internal.h b/src/include/storage/shmem_internal.h
index 8746b614fa3..8cf6a835e1e 100644
--- a/src/include/storage/shmem_internal.h
+++ b/src/include/storage/shmem_internal.h
@@ -13,6 +13,7 @@
 #ifndef SHMEM_INTERNAL_H
 #define SHMEM_INTERNAL_H
 
+#include "nodes/pg_list.h"
 #include "storage/shmem.h"
 #include "utils/hsearch.h"
 
@@ -36,7 +37,7 @@ extern void ResetShmemAllocator(void);
 
 extern void ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind);
 
-extern size_t ShmemGetRequestedSize(void);
+extern List *ShmemPlanRequestedLayout(void);
 extern void ShmemInitRequested(void);
 #ifdef EXEC_BACKEND
 extern void ShmemAttachRequested(void);
diff --git a/src/test/modules/test_shmem/Makefile b/src/test/modules/test_shmem/Makefile
index fed8e29c8f5..0fb1e000906 100644
--- a/src/test/modules/test_shmem/Makefile
+++ b/src/test/modules/test_shmem/Makefile
@@ -8,7 +8,8 @@ export enable_injection_points
 MODULE_big = test_shmem
 OBJS = \
 	$(WIN32RES) \
-	test_shmem.o
+	test_shmem.o \
+	test_resizable_shmem.o
 
 EXTENSION = test_shmem
 DATA = test_shmem--1.0.sql
diff --git a/src/test/modules/test_shmem/meson.build b/src/test/modules/test_shmem/meson.build
index 8f98f2c4e31..4c35ff3daa5 100644
--- a/src/test/modules/test_shmem/meson.build
+++ b/src/test/modules/test_shmem/meson.build
@@ -2,6 +2,7 @@
 
 test_shmem_sources = files(
   'test_shmem.c',
+  'test_resizable_shmem.c',
 )
 
 if host_system == 'windows'
@@ -31,6 +32,7 @@ tests += {
     },
     'tests': [
       't/001_late_shmem_alloc.pl',
+      't/002_resizable_shmem_struct.pl',
     ],
   },
 }
diff --git a/src/test/modules/test_shmem/t/002_resizable_shmem_struct.pl b/src/test/modules/test_shmem/t/002_resizable_shmem_struct.pl
new file mode 100644
index 00000000000..a7ac6883f92
--- /dev/null
+++ b/src/test/modules/test_shmem/t/002_resizable_shmem_struct.pl
@@ -0,0 +1,576 @@
+# Copyright (c) 2025-2026, PostgreSQL Global Development Group
+#
+# Test resizability of shared memory structures
+
+use strict;
+use warnings FATAL => 'all';
+
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+# Verify that enough shared memory is allocated to cover the resizable_shmem
+# structure at its current size but does not exceed the memory required by the
+# current sizes of all shared memory structures. We expect that the backend
+# where we run the query will have touched the entire resizable_shmem structure,
+# so that all the memory pages covering the resizable structure are mapped to
+# the backend's address space.
+#
+# Since we have configured the server so that resizable shared struture
+# dominates the main shared memory segment, the total memory allocated to other
+# shared memory structures does not result in false positive tests below.
+sub check_shmem_usage
+{
+	my ($session, $label, $node) = @_;
+
+	my $shmem_usage =
+	  $session->query_safe('SELECT test_shmem_usage();', verbose => 0);
+	my $total_alloc = $node->safe_psql('postgres',
+		"SELECT sum(allocated_size) FROM pg_shmem_allocations;");
+	my $resizable_alloc = $node->safe_psql('postgres',
+		"SELECT allocated_size FROM pg_shmem_allocations WHERE name = 'resizable_shmem';"
+	);
+
+	diag
+	  "$label: shmem_usage=$shmem_usage, resizable_shmem allocated=$resizable_alloc, sum(allocated_size)=$total_alloc";
+	ok( $shmem_usage <= $total_alloc,
+		"$label: allocated shared memory does not exceed total allocated size"
+	);
+	ok($shmem_usage >= $resizable_alloc,
+		"$label: shared memory usage covers the resizable_shmem allocation");
+}
+
+# Test a resize operation: resize, verify old data, write new data, verify
+# new data, and check shmem usage.  Returns updated ($num_entries, $value).
+sub test_resize
+{
+	my ($node, $prefix, $old_num_entries, $old_value, $new_num_entries,
+		$new_value, $label)
+	  = @_;
+
+	$label = "$prefix: $label";
+
+	my $session1 = $node->background_psql('postgres');
+	my $session2 = $node->background_psql('postgres');
+
+	is( $session1->query_safe(
+			"SELECT resizable_shmem_resize($new_num_entries);",
+			verbose => 0),
+		't',
+		"resize succeeds for $label");
+
+	# Usually an extension would include a step to apply new protection after
+	# resizing in all the backends synchronously. The test_resizable_shmem
+	# extension doesn't do it to keep it simple. Add explicit calls to
+	# resizable_shmem_protect() for each session that matters.
+	$session1->query_safe('SELECT resizable_shmem_protect();');
+	$session2->query_safe('SELECT resizable_shmem_protect();');
+
+	# Old data should still be intact in the (possibly smaller) area
+	my $readable_entries =
+	  ($new_num_entries < $old_num_entries)
+	  ? $new_num_entries
+	  : $old_num_entries;
+	is( $session1->query_safe(
+			"SELECT resizable_shmem_read($readable_entries, $old_value);",
+			verbose => 0),
+		't',
+		"old data readable after $label");
+
+	$session2->query_safe("SELECT resizable_shmem_write($new_value);",
+		verbose => 0);
+	is( $session1->query_safe(
+			"SELECT resizable_shmem_read($new_num_entries, $new_value);",
+			verbose => 0),
+		't',
+		"new data readable after $label");
+
+	check_shmem_usage($session1, "$label (session 1)", $node);
+	check_shmem_usage($session2, "$label (session 2)", $node);
+
+	# A new backend is able to access the entire structure.
+	is( $node->safe_psql(
+			'postgres',
+			"SELECT resizable_shmem_read($new_num_entries, $new_value);"),
+		't',
+		"new backend reads data after $label without explicit protection");
+
+	$session1->quit;
+	$session2->quit;
+
+	return ($new_num_entries, $new_value);
+}
+
+# Verify that reads or writes past the current size fault when they reach the
+# protected region.
+sub test_fault_beyond_size
+{
+	my ($node, $initial_entries, $prefix) = @_;
+
+	# Enable restart_after_crash to test postmaster driven restart with
+	# resizable shared memory.
+	$node->safe_psql('postgres',
+		'ALTER SYSTEM SET restart_after_crash = on;');
+	$node->reload;
+
+	for my $mode ('write', 'read')
+	{
+		# Session for resizing
+		my $session = $node->background_psql('postgres');
+
+		# Session to detect a server restart after crash
+		my $sentinel = $node->background_psql('postgres');
+		my $sentinel_pid = $sentinel->{backend_pid};
+
+		$session->query_until(
+			qr/checking protected access/, qq{
+			\\echo checking protected access
+			SELECT resizable_shmem_access_beyond_size('$mode');
+		});
+
+		# Wait for the postmaster to terminate the sentinel, which indicates a
+		# server crash, and finish recovery.
+		$node->poll_query_until('postgres',
+			"SELECT count(*) = 0 FROM pg_stat_activity WHERE pid = $sentinel_pid"
+		) or die "server did not come back after $mode crash";
+		$sentinel->finish;
+		ok(!$session->finish,
+			"$prefix: $mode past current size crashes the backend");
+		like(
+			$session->{stderr},
+			qr/server closed the connection unexpectedly|connection to server was lost/,
+			"$prefix: $mode crash reports lost connection");
+
+	}
+
+	is( $node->safe_psql(
+			'postgres', "SELECT resizable_shmem_read($initial_entries, 0);"),
+		't',
+		"$prefix: read succeeds after crash recovery");
+
+	$node->safe_psql('postgres', 'ALTER SYSTEM RESET restart_after_crash;');
+	$node->reload;
+}
+
+# Failure to allocate memory during expansion must leave the structure in the
+# same state, metadata, data memory protection and allocated memory, as before
+# the expansion attempt.
+sub test_allocation_failure
+{
+	my ($node, $old_entries, $old_value, $max_entries, $prefix) = @_;
+
+	my $metadata_query =
+	  "SELECT size, allocated_size, minimum_size, maximum_size, reserved_space,
+	          test_shmem_usage()
+	   FROM pg_shmem_allocations WHERE name = 'resizable_shmem';";
+
+  SKIP:
+	{
+		# Use injection points to simulate allocation failure.
+		skip "$prefix: injection points unavailable"
+		  if $ENV{enable_injection_points} ne 'yes';
+		cmp_ok($old_entries, '>', 0,
+			"$prefix: allocation failure starts with existing data");
+		$node->safe_psql(
+			'postgres',
+			"SELECT injection_points_attach('shmem-allocate', 'test_shmem',
+			 'test_shmem_allocate_fail', NULL);");
+
+		my $session = $node->background_psql('postgres', on_error_stop => 0);
+
+		# Read the existing state of the structure.
+		#
+		# This will populate the memory pages in this backend's address space so
+		# that we will be able to assess memory usage from this backend.
+		is( $session->query_safe(
+				"SELECT resizable_shmem_read($old_entries, $old_value);"),
+			't',
+			"$prefix: data readable before allocation failure");
+		my $md_before = $session->query_safe($metadata_query);
+
+		# Attempt to expand the structure to the maximum so that the expansion
+		# requires allocating more memory pages.
+		is( scalar $session->query(
+				"SELECT resizable_shmem_resize($max_entries);"),
+			'f',
+			"$prefix: allocation failure returns false");
+		like(
+			$session->{stderr},
+			qr/could not allocate .* shared memory to structure "resizable_shmem"/,
+			"$prefix: allocation failure reports warning");
+
+		# Make sure that the state of the structure remains unchanged
+		$session->{stderr} = '';
+		is($session->query_safe($metadata_query), $md_before,
+			"$prefix: failure preserves allocation metadata and memory usage"
+		);
+		is( $session->query_safe(
+				"SELECT resizable_shmem_read($old_entries, $old_value);"),
+			't',
+			"$prefix: failure preserves data");
+		$node->safe_psql('postgres',
+			"SELECT injection_points_detach('shmem-allocate');");
+
+		# Check that the memory protection is consistent with the current size,
+		# by trying to access memory beyond the current allocation.
+		$node->safe_psql('postgres',
+			'ALTER SYSTEM SET restart_after_crash = on;');
+		$node->reload;
+
+		my $sentinel = $node->background_psql('postgres');
+		my $sentinel_pid = $sentinel->{backend_pid};
+
+		$session->query_until(
+			qr/checking rollback protection/, qq{
+			\\echo checking rollback protection
+			SELECT resizable_shmem_access_beyond_size('read');
+		});
+
+		# Wait for the postmaster to terminate the sentinel, which indicates a
+		# server crash, and finish recovery.
+		$node->poll_query_until('postgres',
+			"SELECT count(*) = 0 FROM pg_stat_activity WHERE pid = $sentinel_pid"
+		) or die 'server did not recover after rollback protection test';
+		$sentinel->finish;
+		ok(!$session->finish,
+			"$prefix: failed expansion restores inaccessible pages");
+		like(
+			$session->{stderr},
+			qr/server closed the connection unexpectedly|connection to server was lost/,
+			"$prefix: access after failed expansion faults");
+
+		$node->safe_psql('postgres',
+			'ALTER SYSTEM RESET restart_after_crash;');
+		$node->reload;
+	}
+}
+
+# Run the full suite of resizable shared memory tests on the given node.
+sub run_resizable_tests
+{
+	my ($node, $initial_entries, $max_entries, $prefix) = @_;
+	my $have_resizable_shmem =
+	  $node->safe_psql('postgres', 'SHOW have_resizable_shmem;') eq 'on';
+
+	my $num_entries = $initial_entries;
+
+	# Basic read/write should work on all platforms
+	my $value = 100;
+	$node->safe_psql('postgres', "SELECT resizable_shmem_write($value);");
+	is( $node->safe_psql(
+			'postgres', "SELECT resizable_shmem_read($num_entries, $value);"),
+		't',
+		"$prefix: data read after write successful");
+
+	if ($have_resizable_shmem)
+	{
+		# Initial structure state
+		my $session1 = $node->background_psql('postgres');
+		my $session2 = $node->background_psql('postgres');
+
+		$value = 100;
+		# Write and read the initial set of entries.
+		$session1->query_safe("SELECT resizable_shmem_write($value);",
+			verbose => 0);
+		is( $session2->query_safe(
+				"SELECT resizable_shmem_read($num_entries, $value);",
+				verbose => 0),
+			't',
+			"$prefix: data read after write successful");
+		check_shmem_usage($session1, "$prefix: initial write (session 1)",
+			$node);
+		check_shmem_usage($session2, "$prefix: initial write (session 2)",
+			$node);
+		$session1->quit;
+		$session2->quit;
+
+		# Verify no other structure is resizable
+		is( $node->safe_psql(
+				'postgres',
+				"SELECT count(*) FROM pg_shmem_allocations WHERE name <> 'resizable_shmem' AND maximum_size <> minimum_size;"
+			),
+			'0',
+			"$prefix: no other resizable structures");
+
+		# Resize to maximum
+		($num_entries, $value) =
+		  test_resize($node, $prefix, $num_entries, $value,
+			$max_entries, 500, 'resize to maximum');
+
+		# Shrink to 75% of max
+		my $shrink_entries = int($max_entries * 3 / 4);
+		($num_entries, $value) =
+		  test_resize($node, $prefix, $num_entries, $value,
+			$shrink_entries, 999, 'shrinking');
+
+		# Resize to the same size (no-op)
+		($num_entries, $value) =
+		  test_resize($node, $prefix, $num_entries, $value,
+			$num_entries, 1999, 'no-op resize');
+
+		# Shrink to minimum
+		($num_entries, $value) =
+		  test_resize($node, $prefix, $num_entries, $value, 0, 0,
+			'shrink to minimum');
+
+		# Grow back and populate data to check after allocation failure.
+		($num_entries, $value) =
+		  test_resize($node, $prefix, $num_entries, $value,
+			$initial_entries, 2999, 'grow back from minimum');
+
+		# Allocation failure test and memory protection verification require a
+		# memory hole in the structure.  A gap in the current and maximal end of
+		# the structure larger than two pages guarantees such a hole.
+		my $has_room = $node->safe_psql(
+			'postgres', qq{
+			SELECT maximum_size - size > 2 * test_shmem_pagesize()
+			FROM pg_shmem_allocations WHERE name = 'resizable_shmem';
+		});
+	  SKIP:
+		{
+			skip "$prefix: expansion space does not exceed two pages"
+			  if $has_room ne 't';
+
+			test_allocation_failure($node, $num_entries, $value, $max_entries,
+				$prefix);
+			test_fault_beyond_size($node, $initial_entries, $prefix);
+		}
+
+		# Test resize failure (attempt to resize beyond max - should fail)
+		my ($ret, $stdout, $stderr) =
+		  $node->psql('postgres',
+			"SELECT resizable_shmem_resize(" . ($max_entries * 2) . ");");
+		ok( $ret != 0 || $stderr =~ /ERROR/,
+			"$prefix: Resize beyond maximum fails");
+
+		# Resize to a size below minimum_size must fail.
+		($ret, $stdout, $stderr) =
+		  $node->psql('postgres', 'SELECT resizable_shmem_resize(-1);');
+		ok($ret != 0, "$prefix: resize below minimum_size fails");
+		like(
+			$stderr,
+			qr/cannot shrink shared memory structure "resizable_shmem" below minimum size/,
+			"$prefix: resize-below-minimum error comes from ShmemResizeStruct"
+		);
+
+	}
+	else
+	{
+		# On unsupported platforms, resizing should fail with a clear error
+		my ($ret, $stdout, $stderr) =
+		  $node->psql('postgres',
+			"SELECT resizable_shmem_resize($num_entries);");
+		ok($ret != 0, "$prefix: resize fails on unsupported platform");
+		like(
+			$stderr,
+			qr/not supported/,
+			"$prefix: resize error mentions not supported");
+	}
+}
+
+# Check the runtime-computed shared_memory_{initial,minimum,maximum}_size GUC
+# invariants.  min <= initial <= max must always hold.  When a resizable
+# structure has been registered on a server that supports resizable shared
+# memory structures, min must additionally be strictly less than max;
+# otherwise all three GUCs must be equal.
+sub check_shmem_size_gucs
+{
+	my ($node, $label, $have_resizable_struct) = @_;
+	my $pgdata = $node->data_dir;
+
+	my $get = sub {
+		my ($guc) = @_;
+		my ($stdout, $stderr);
+		IPC::Run::run(
+			[ 'postgres', '-D' => $pgdata, '-C' => $guc ],
+			'>' => \$stdout,
+			'2>' => \$stderr) or die "postgres -C $guc failed: $stderr";
+
+		chomp($stdout);
+		return $stdout;
+	};
+
+	my $have_resizable_shmem = $get->('have_resizable_shmem');
+	my $ini = 0 + $get->('shared_memory_initial_size');
+	my $min = 0 + $get->('shared_memory_minimum_size');
+	my $max = 0 + $get->('shared_memory_maximum_size');
+
+	ok($min <= $ini && $ini <= $max,
+		"$label: shared_memory size GUCs in expected order");
+
+	if ($have_resizable_struct && $have_resizable_shmem eq 'on')
+	{
+		ok($min < $max, "$label: min < max with resizable structures");
+	}
+	else
+	{
+		ok( $min == $ini && $ini == $max,
+			"$label: all shared_memory size GUCs equal when no resizable structures"
+		);
+	}
+}
+
+# Log the runtime shared_memory_{initial,minimum,maximum}_size GUCs and huge
+# pages usage information for easier debugging.
+sub diag_shmem_sizes
+{
+	my ($node, $label) = @_;
+
+	my $vals = $node->safe_psql(
+		'postgres', q{
+		SELECT format('initial=%s minimum=%s maximum=%s huge_pages_status=%s huge_page_size=%s shmem_page_size=%s',
+					  current_setting('shared_memory_initial_size'),
+					  current_setting('shared_memory_minimum_size'),
+					  current_setting('shared_memory_maximum_size'),
+					  current_setting('huge_pages_status'),
+					  current_setting('huge_page_size'),
+					  test_shmem_pagesize());
+	});
+	diag "$label: $vals";
+}
+
+### Set up a test node.
+#
+# Configure minimal shared memory so that the resizable_shmem structure dominates
+# and any unexpected increase is easy to detect.
+#
+# If we turn on huge pages and the machine where the test is running does not
+# have huge pages available, the test will fail midway because it will not be
+# able to allocate memory pages when expanding the resizable_shmem structure.
+# Hence we turn off huge pages for this test. The test outputs the GUCs
+# shared_memory_{initial,minimum,maximum}_size and information about huge pages.
+# By provisioning enough huge pages, and by changing huge_pages = try/on, the
+# test can be run with huge pages enabled.
+###
+my $node = PostgreSQL::Test::Cluster->new('resizable_shmem');
+$node->init;
+
+$node->append_conf('postgresql.conf', 'huge_pages = off');
+$node->append_conf('postgresql.conf', 'shared_buffers = 128kB');
+$node->append_conf('postgresql.conf', 'max_connections = 5');
+$node->append_conf('postgresql.conf', 'max_worker_processes = 0');
+$node->append_conf('postgresql.conf', 'max_wal_senders = 0');
+$node->append_conf('postgresql.conf', 'max_prepared_transactions = 0');
+$node->append_conf('postgresql.conf', 'max_locks_per_transaction = 10');
+$node->append_conf('postgresql.conf', 'max_pred_locks_per_transaction = 10');
+$node->append_conf('postgresql.conf', 'wal_buffers = 32kB');
+
+###
+# Test 1: Startup allocation via shared_preload_libraries
+###
+my $startup_initial = 25 * 1024 * 1024;
+my $startup_max = 100 * 1024 * 1024;
+
+# We preload injection_points library always if it's available, but may not need
+# test_shmem depending upon the test.
+my $injection_preload_lib =
+  $ENV{enable_injection_points} eq 'yes' ? 'injection_points' : '';
+my $test_shmem_preload_libs = 'test_shmem'
+  . ($injection_preload_lib ne '' ? ",$injection_preload_lib" : '');
+
+$node->append_conf('postgresql.conf',
+	"shared_preload_libraries = '$test_shmem_preload_libs'");
+$node->append_conf('postgresql.conf',
+	"resizable_shmem.initial_entries = $startup_initial");
+$node->append_conf('postgresql.conf',
+	"resizable_shmem.max_entries = $startup_max");
+
+check_shmem_size_gucs($node, 'startup preload', 1);
+
+$node->start;
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points;')
+  if $ENV{enable_injection_points} eq 'yes';
+$node->safe_psql('postgres', 'CREATE EXTENSION test_shmem;');
+diag_shmem_sizes($node, 'startup');
+run_resizable_tests($node, $startup_initial, $startup_max, 'startup');
+
+my $have_resizable_shmem =
+  $node->safe_psql('postgres', 'SHOW have_resizable_shmem;') eq 'on';
+
+###
+# Test that a fixed-size shared memory structure cannot be resized.
+# Only relevant on platforms that support resizable shmem.
+###
+if ($have_resizable_shmem)
+{
+	# Try expanding the fixed-size structure
+	my ($ret, $stdout, $stderr) =
+	  $node->psql("postgres", "SELECT test_shmem_resize_fixed(1000);");
+	isnt($ret, 0, "expanding a fixed-size structure fails");
+	like(
+		$stderr,
+		qr/is not resizable/,
+		"expand error message mentions not resizable");
+
+	# Try shrinking the fixed-size structure
+	($ret, $stdout, $stderr) =
+	  $node->psql("postgres", "SELECT test_shmem_resize_fixed(1);");
+	isnt($ret, 0, "shrinking a fixed-size structure fails");
+	like(
+		$stderr,
+		qr/is not resizable/,
+		"shrink error message mentions not resizable");
+}
+
+###
+# Test that minimum_size and maximum_size equal size for a fixed-size structure
+# in pg_shmem_allocations.
+###
+is( $node->safe_psql(
+		'postgres',
+		"SELECT minimum_size = size AND maximum_size = size FROM pg_shmem_allocations WHERE name = 'test_shmem area';"
+	),
+	't',
+	"fixed-size structure has minimum_size = maximum_size = size");
+
+###
+# Test sysv shared memory does not support resizable shmem.  Only relevant on
+# platforms that support resizable shmem (HAVE_RESIZABLE_SHMEM), since the
+# module only sets maximum_size in that case.
+###
+if ($have_resizable_shmem)
+{
+	###
+	# Test 2: SysV shared memory reports resizing as unsupported.
+	###
+	$node->safe_psql('postgres', 'DROP EXTENSION test_shmem;');
+
+	$node->safe_psql(
+		'postgres', qq{
+		ALTER SYSTEM SET shared_preload_libraries = '$injection_preload_lib';
+		ALTER SYSTEM SET shared_memory_type = 'sysv';
+	});
+
+	$node->stop;
+
+	check_shmem_size_gucs($node, 'sysv', 0);
+
+	$node->start;
+
+	is($node->safe_psql('postgres', 'SHOW have_resizable_shmem;'),
+		'off',
+		'have_resizable_shmem reports off with shared_memory_type = sysv');
+
+	###
+	# Test 3: Verify that resizable structures are rejected with sysv
+	# shared memory when loaded at startup via shared_preload_libraries.
+	###
+	$node->safe_psql(
+		'postgres', qq{
+		ALTER SYSTEM SET shared_preload_libraries = 'test_shmem';
+		ALTER SYSTEM SET resizable_shmem.initial_entries = $startup_initial;
+		ALTER SYSTEM SET resizable_shmem.max_entries = $startup_max;
+	});
+	$node->stop;
+
+	ok(!$node->start(fail_ok => 1),
+		'server fails to start with resizable shmem on sysv');
+
+	my $log = slurp_file($node->logfile);
+	like(
+		$log,
+		qr/resizable shared memory requires shared_memory_type = mmap/,
+		'log mentions shared_memory_type = mmap requirement');
+}
+
+done_testing();
diff --git a/src/test/modules/test_shmem/test_resizable_shmem.c b/src/test/modules/test_shmem/test_resizable_shmem.c
new file mode 100644
index 00000000000..74a5938f8d5
--- /dev/null
+++ b/src/test/modules/test_shmem/test_resizable_shmem.c
@@ -0,0 +1,443 @@
+/*-------------------------------------------------------------------------
+ *
+ * test_resizable_shmem.c
+ *		Helpers to test resizable shmem management routines
+ *
+ * Copyright (c) 2020-2026, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ *	  src/test/modules/test_shmem/test_resizable_shmem.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres.h"
+
+#include <limits.h>
+
+#include "fmgr.h"
+#include "miscadmin.h"
+#include "storage/fd.h"
+#include "storage/pg_shmem.h"
+#include "storage/shmem.h"
+#include "test_resizable_shmem.h"
+#include "utils/builtins.h"
+#include "utils/guc.h"
+#include "utils/injection_point.h"
+
+
+/*
+ * GUC variables controlling the size of the test structure and their defaults.
+ * The defaults are intentionally low so that the tests other than resizing
+ * tests use minimal shared memory.
+ */
+#define TEST_INITIAL_ENTRIES_DEFAULT		1
+#define TEST_MAX_ENTRIES_DEFAULT			1024
+
+static int	test_initial_entries = TEST_INITIAL_ENTRIES_DEFAULT;
+static int	test_max_entries = TEST_MAX_ENTRIES_DEFAULT;
+
+
+/*
+ * Resizable test data structure stored in shared memory.
+ *
+ * The test performs resizing, reads or writes, only one at a time and never
+ * concurrently. Hence, there is no need for locks in the test structure.
+ */
+#define TEST_ENTRY_SIZE			sizeof(int32)	/* Size of each entry */
+typedef struct TestResizableShmemStruct
+{
+	/* Metadata */
+	int32		num_entries;	/* Size of the data array */
+
+	/* Data area - variable size */
+	int32		data[FLEXIBLE_ARRAY_MEMBER];
+} TestResizableShmemStruct;
+
+static TestResizableShmemStruct *resizable_shmem = NULL;
+
+/*
+ * Request shared memory resources.
+ */
+static void
+resizable_shmem_request(void *arg)
+{
+	Size		initial_size = add_size(offsetof(TestResizableShmemStruct, data),
+										mul_size(test_initial_entries, TEST_ENTRY_SIZE));
+
+/*
+ * Create resizable structure on the platforms which support it. Otherwise create
+ * as a fixed-size structure.
+ */
+#ifdef HAVE_RESIZABLE_SHMEM
+	Size		max_size = add_size(offsetof(TestResizableShmemStruct, data),
+									mul_size(test_max_entries, TEST_ENTRY_SIZE));
+	Size		min_size = offsetof(TestResizableShmemStruct, data);
+#else
+	Size		max_size = 0;
+	Size		min_size = 0;
+#endif
+
+	ShmemRequestStruct(.name = "resizable_shmem",
+					   .size = initial_size,
+					   .minimum_size = min_size,
+					   .maximum_size = max_size,
+					   .ptr = (void **) &resizable_shmem,
+		);
+}
+
+/*
+ * Initialize shared memory structure.
+ */
+static void
+resizable_shmem_shmem_init(void *arg)
+{
+	Assert(resizable_shmem != NULL);
+
+	resizable_shmem->num_entries = test_initial_entries;
+	memset(resizable_shmem->data, 0, mul_size(test_initial_entries, TEST_ENTRY_SIZE));
+}
+
+/*
+ * Attach to the already-allocated shared memory structure.
+ */
+static void
+resizable_shmem_shmem_attach(void *arg)
+{
+	Assert(resizable_shmem != NULL);
+}
+
+static ShmemCallbacks resizable_shmem_callbacks = {
+	.request_fn = resizable_shmem_request,
+	.init_fn = resizable_shmem_shmem_init,
+	.attach_fn = resizable_shmem_shmem_attach,
+};
+
+/*
+ * Resize the shared memory structure to accommodate the specified number of
+ * entries.
+ *
+ * Negative value for new_entries can be used to test resizing below the
+ * minimum size.
+ *
+ * Returns true if the resize was successful, false if ShmemResizeStruct()
+ * could not allocate the requested memory.  On platforms that do not support
+ * resizable shared memory, ShmemResizeStruct() raises an error.
+ */
+PG_FUNCTION_INFO_V1(resizable_shmem_resize);
+Datum
+resizable_shmem_resize(PG_FUNCTION_ARGS)
+{
+	int32		new_entries = PG_GETARG_INT32(0);
+	Size		new_size;
+
+	if (!resizable_shmem)
+		ereport(ERROR,
+				errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				errmsg("resizable_shmem is not initialized"));
+
+	if (new_entries < 0)
+		new_size = 1;
+	else
+		new_size = add_size(offsetof(TestResizableShmemStruct, data),
+							mul_size(new_entries, TEST_ENTRY_SIZE));
+	if (!ShmemResizeStruct("resizable_shmem", new_size))
+		PG_RETURN_BOOL(false);
+
+	resizable_shmem->num_entries = new_entries;
+
+	PG_RETURN_BOOL(true);
+}
+
+/*
+ * Adjust memory address protection of the resizable shared memory structure
+ * according to its current size in this backend.
+ *
+ * Usually an extension would perform this step after resizing the structure
+ * across all backend in a synchronous fashion. But we provide a separate
+ * function for tests to apply protection in each backend individually in each
+ * backend and avoid the complexity of synchronization.
+ */
+PG_FUNCTION_INFO_V1(resizable_shmem_protect);
+Datum
+resizable_shmem_protect(PG_FUNCTION_ARGS)
+{
+	if (!resizable_shmem)
+		ereport(ERROR,
+				errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				errmsg("resizable_shmem is not initialized"));
+
+	ShmemProtectStruct("resizable_shmem");
+	PG_RETURN_VOID();
+}
+
+/*
+ * Write the given integer value to all entries in the data array.
+ */
+PG_FUNCTION_INFO_V1(resizable_shmem_write);
+Datum
+resizable_shmem_write(PG_FUNCTION_ARGS)
+{
+	int32		entry_value = PG_GETARG_INT32(0);
+	int32		i;
+
+	if (!resizable_shmem)
+		ereport(ERROR,
+				errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				errmsg("resizable_shmem is not initialized"));
+
+	for (i = 0; i < resizable_shmem->num_entries; i++)
+		resizable_shmem->data[i] = entry_value;
+
+	PG_RETURN_VOID();
+}
+
+/*
+ * Check whether the first 'entry_count' entries all have the expected 'entry_value'.
+ * Returns true if all match, false otherwise.
+ */
+PG_FUNCTION_INFO_V1(resizable_shmem_read);
+Datum
+resizable_shmem_read(PG_FUNCTION_ARGS)
+{
+	int32		entry_count = PG_GETARG_INT32(0);
+	int32		entry_value = PG_GETARG_INT32(1);
+	int32		i;
+
+	if (resizable_shmem == NULL)
+		ereport(ERROR,
+				errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				errmsg("resizable_shmem is not initialized"));
+
+	if (entry_count < 0 || entry_count > resizable_shmem->num_entries)
+		ereport(ERROR,
+				errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				errmsg("entry_count %d is out of range (0..%d)", entry_count, resizable_shmem->num_entries));
+
+	for (i = 0; i < entry_count; i++)
+	{
+		if (resizable_shmem->data[i] != entry_value)
+			PG_RETURN_BOOL(false);
+	}
+
+	PG_RETURN_BOOL(true);
+}
+
+/*
+ * Return the memory mapped against the main shared memory segment in this
+ * backend.
+ *
+ * The VMA containing our resizable_shmem pointer identifies the start of the
+ * main shared-memory segment.  mprotect() can split that mapping into adjacent
+ * VMAs, so include adjacent VMAs that share the same shared/private flag,
+ * inode, and pathname as the target VMA.
+ */
+PG_FUNCTION_INFO_V1(test_shmem_usage);
+Datum
+test_shmem_usage(PG_FUNCTION_ARGS)
+{
+	FILE	   *f;
+	char		line[256];
+	uintptr_t	target = (uintptr_t) resizable_shmem;
+	bool		in_target_vma = false;
+	bool		target_is_shared = false;
+	unsigned long target_inode = 0;
+	char		target_path[256] = "";
+	bool		use_hugetlb = (huge_pages_status == HUGE_PAGES_ON);
+	unsigned long prev_end = 0;
+	long		total_rss_kb = 0;
+	long		total_swap_kb = 0;
+	long		total_shared_hugetlb_kb = 0;
+	long		val;
+	size_t		result;
+
+	f = AllocateFile("/proc/self/smaps", "r");
+	if (f == NULL)
+		ereport(ERROR,
+				errcode_for_file_access(),
+				errmsg("could not open /proc/self/smaps: %m"));
+
+	while (fgets(line, sizeof(line), f) != NULL)
+	{
+		unsigned long start;
+		unsigned long end;
+		unsigned long offset;
+		unsigned long inode;
+		char		perms[8];
+		char		dev[16];
+		char		path[256] = "";
+
+		if (sscanf(line, "%lx-%lx %7s %lx %15s %lu %255[^\n]",
+				   &start, &end, perms, &offset, dev, &inode, path) >= 6)
+		{
+			if (in_target_vma)
+			{
+				if (start != prev_end
+					|| (perms[3] == 's') != target_is_shared
+					|| inode != target_inode
+					|| strcmp(path, target_path) != 0)
+					break;
+
+				elog(DEBUG1, "test_shmem smaps includes contiguous VMA: %.*s",
+					 (int) strcspn(line, "\n"), line);
+			}
+			else if (target >= start && target < end)
+			{
+				in_target_vma = true;
+				target_is_shared = (perms[3] == 's');
+				target_inode = inode;
+				strlcpy(target_path, path, sizeof(target_path));
+
+				elog(DEBUG1, "test_shmem smaps includes target VMA: %.*s",
+					 (int) strcspn(line, "\n"), line);
+			}
+
+			prev_end = end;
+		}
+		else if (in_target_vma)
+		{
+			if (use_hugetlb)
+			{
+				if (sscanf(line, "Shared_Hugetlb: %ld kB", &val) == 1)
+					total_shared_hugetlb_kb += val;
+			}
+			else
+			{
+				if (sscanf(line, "Rss: %ld kB", &val) == 1)
+					total_rss_kb += val;
+				else if (sscanf(line, "Swap: %ld kB", &val) == 1)
+					total_swap_kb += val;
+			}
+		}
+	}
+
+	FreeFile(f);
+
+	if (use_hugetlb)
+		result = mul_size(total_shared_hugetlb_kb, 1024);
+	else
+	{
+		result = mul_size(total_rss_kb, 1024);
+		result = add_size(result, mul_size(total_swap_kb, 1024));
+	}
+
+	PG_RETURN_INT64(result);
+}
+
+/*
+ * Return the shared memory page size.
+ */
+PG_FUNCTION_INFO_V1(test_shmem_pagesize);
+Datum
+test_shmem_pagesize(PG_FUNCTION_ARGS)
+{
+	PG_RETURN_INT32(pg_get_shmem_pagesize());
+}
+
+/*
+ * Access the first byte of the first whole page beyond the current size, which
+ * should trigger a fault, if there's a hole at the place. Raise an error if such
+ * a hole does not exist since we expect this function to be called to test the
+ * fault.
+ */
+PG_FUNCTION_INFO_V1(resizable_shmem_access_beyond_size);
+Datum
+resizable_shmem_access_beyond_size(PG_FUNCTION_ARGS)
+{
+	text	   *mode_txt = PG_GETARG_TEXT_PP(0);
+	const char *mode = text_to_cstring(mode_txt);
+	bool		do_write;
+	int32		sink = 0;
+	Size		page_size = pg_get_shmem_pagesize();
+	unsigned char *reserved_end;
+	unsigned char *protected_start;
+
+	if (!resizable_shmem)
+		ereport(ERROR,
+				errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				errmsg("resizable_shmem is not initialized"));
+
+	if (strcmp(mode, "read") == 0)
+		do_write = false;
+	else if (strcmp(mode, "write") == 0)
+		do_write = true;
+	else
+		ereport(ERROR,
+				errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				errmsg("mode must be \"read\" or \"write\""));
+
+	/*
+	 * Estimate the start of the memory hole after the current size based on
+	 * the page size alignment and structure layout.
+	 */
+	protected_start = (unsigned char *) TYPEALIGN(page_size,
+												  resizable_shmem->data + resizable_shmem->num_entries);
+	reserved_end = (unsigned char *) TYPEALIGN_DOWN(page_size,
+													resizable_shmem->data + test_max_entries);
+	if (protected_start >= reserved_end)
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				 errmsg("resizable shared memory structure has no protected whole page")));
+
+	if (do_write)
+		*protected_start = 0xad;
+	else
+		sink = *protected_start;
+
+	/*
+	 * Return the read value so that the compiler doesn't optimize away the
+	 * assignment to sink.
+	 */
+	PG_RETURN_INT32(sink);
+}
+
+/*
+ * Register GUCs and shmem callbacks for the resizable shared memory
+ * structure.  Called from _PG_init() in test_shmem.c.
+ */
+void
+ResizableShmemInit(void)
+{
+	/* Resizable shared memory structures are not supported after startup. */
+	if (!process_shared_preload_libraries_in_progress)
+		return;
+
+	DefineCustomIntVariable("resizable_shmem.initial_entries",
+							"Initial number of entries in the test structure.",
+							NULL,
+							&test_initial_entries,
+							TEST_INITIAL_ENTRIES_DEFAULT,
+							1,
+							INT_MAX,
+							PGC_POSTMASTER,
+							0,
+							NULL, NULL, NULL);
+
+	DefineCustomIntVariable("resizable_shmem.max_entries",
+							"Maximum number of entries in the test structure.",
+							NULL,
+							&test_max_entries,
+							TEST_MAX_ENTRIES_DEFAULT,
+							1,
+							INT_MAX,
+							PGC_POSTMASTER,
+							0,
+							NULL, NULL, NULL);
+
+	RegisterShmemCallbacks(&resizable_shmem_callbacks);
+}
+
+/* Injection point callback for simulating shared memory allocation failure. */
+#ifdef USE_INJECTION_POINTS
+extern PGDLLEXPORT void test_shmem_allocate_fail(const char *name,
+												 const void *private_data,
+												 void *arg);
+
+void
+test_shmem_allocate_fail(const char *name, const void *private_data, void *arg)
+{
+	bool	   *simulate_failure = (bool *) arg;
+
+	*simulate_failure = true;
+}
+#endif
diff --git a/src/test/modules/test_shmem/test_resizable_shmem.h b/src/test/modules/test_shmem/test_resizable_shmem.h
new file mode 100644
index 00000000000..0a2610bee57
--- /dev/null
+++ b/src/test/modules/test_shmem/test_resizable_shmem.h
@@ -0,0 +1,18 @@
+/*-------------------------------------------------------------------------
+ *
+ * test_resizable_shmem.h
+ *		Definitions for the resizable shmem test module
+ *
+ * Copyright (c) 2020-2026, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ *	  src/test/modules/test_shmem/test_resizable_shmem.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TEST_RESIZABLE_SHMEM_H
+#define TEST_RESIZABLE_SHMEM_H
+
+extern void ResizableShmemInit(void);
+
+#endif							/* TEST_RESIZABLE_SHMEM_H */
diff --git a/src/test/modules/test_shmem/test_shmem--1.0.sql b/src/test/modules/test_shmem/test_shmem--1.0.sql
index 1dec3ce0d68..21b5ec6a384 100644
--- a/src/test/modules/test_shmem/test_shmem--1.0.sql
+++ b/src/test/modules/test_shmem/test_shmem--1.0.sql
@@ -4,6 +4,10 @@
 \echo Use "CREATE EXTENSION test_shmem" to load this file. \quit
 
 
+-- ===================================================================
+-- Fixed-size shared memory structure
+-- ===================================================================
+
 CREATE FUNCTION get_test_shmem_attach_count()
 RETURNS pg_catalog.int4 STRICT
 AS 'MODULE_PATHNAME' LANGUAGE C;
@@ -11,3 +15,61 @@ AS 'MODULE_PATHNAME' LANGUAGE C;
 CREATE FUNCTION test_shmem_register(pg_catalog.text, pg_catalog.int8, pg_catalog.int4)
 RETURNS pg_catalog.int4 STRICT
 AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_shmem_resize_fixed(pg_catalog.int4)
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+
+-- ===================================================================
+-- Resizable shared memory structure
+-- ===================================================================
+
+-- Function to resize the test structure in the shared memory
+CREATE FUNCTION resizable_shmem_resize(new_entries integer)
+RETURNS bool
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+-- Apply protection in each participating backend after a successful resize,
+-- before accessing data or starting another resize.
+CREATE FUNCTION resizable_shmem_protect()
+RETURNS void
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+-- Function to write data to all entries in the test structure in shared memory
+-- Writing all the entries makes sure that the memory is actually allocated and
+-- mapped to the process, so that we can later measure the memory usage.
+CREATE FUNCTION resizable_shmem_write(entry_value integer)
+RETURNS void
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+-- Function to verify that specified number of initial entries have expected value.
+-- Reading all the entries makes sure that the memory is actually mapped to the
+-- process, so that we can later measure the memory usage.
+CREATE FUNCTION resizable_shmem_read(entry_count integer, entry_value integer)
+RETURNS boolean
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+-- Function to report memory mapped against the main shared memory segment in
+-- the backend where this function runs.
+CREATE FUNCTION test_shmem_usage()
+RETURNS bigint
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+-- Function to get the shared memory page size
+CREATE FUNCTION test_shmem_pagesize()
+RETURNS integer
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+-- Read or write the first protected byte beyond the current size (and crash the
+-- server).  The structure must have a memory hole in it.
+CREATE FUNCTION resizable_shmem_access_beyond_size(mode text)
+RETURNS integer
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index bb822ea30a8..71fcd3d865c 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -7,6 +7,10 @@
  * that is not exercised by any other module in the repository is the
  * allocating (non-DSM) shared memory after postmaster startup.
  *
+ * This file is also shared for testing resizable shared memory allocations
+ * through the same extension. Also the shared memory structure in this file is
+ * used to test that a fixed size shared memory allocation can not be resized.
+ *
  * Copyright (c) 2020-2026, PostgreSQL Global Development Group
  *
  * IDENTIFICATION
@@ -19,7 +23,9 @@
 
 #include "fmgr.h"
 #include "miscadmin.h"
+#include "storage/ipc.h"
 #include "storage/shmem.h"
+#include "test_resizable_shmem.h"
 #include "utils/builtins.h"
 #include "utils/guc.h"
 #include "utils/injection_point.h"
@@ -46,6 +52,7 @@ static bool test_shmem_guc_defined = false;
 static void test_shmem_request(void *arg);
 static void test_shmem_init(void *arg);
 static void test_shmem_attach(void *arg);
+static void test_shmem_reset(int code, Datum arg);
 
 static const ShmemCallbacks TestShmemCallbacks = {
 	.flags = SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP,
@@ -78,6 +85,9 @@ test_shmem_init(void *arg)
 	if (attached_or_initialized)
 		elog(ERROR, "attach or initialize already called in this process");
 	attached_or_initialized = true;
+
+	/* Arrange to reset the flag on the postmaster induced restart. */
+	on_shmem_exit(test_shmem_reset, 0);
 }
 
 static void
@@ -93,6 +103,12 @@ test_shmem_attach(void *arg)
 	attached_or_initialized = true;
 }
 
+static void
+test_shmem_reset(int code, Datum arg)
+{
+	attached_or_initialized = false;
+}
+
 void
 _PG_init(void)
 {
@@ -102,7 +118,7 @@ _PG_init(void)
 	{
 		/*
 		 * The minimum size that makes sense is sizeof(TestShmemData), but we
-		 * allow -1 so that we can test passing SHMEM_ATTACH_UNKNOWN_SIZE.
+		 * allow -1 so that we can test SHMEM_ATTACH_UNKNOWN_SIZE.
 		 */
 		DefineCustomIntVariable("test_shmem.area_size",
 								"Size of the shmem area to request.",
@@ -117,7 +133,9 @@ _PG_init(void)
 		MarkGUCPrefixReserved("test_shmem");
 		test_shmem_guc_defined = true;
 	}
+
 	RegisterShmemCallbacks(&TestShmemCallbacks);
+	ResizableShmemInit();
 }
 
 PG_FUNCTION_INFO_V1(get_test_shmem_attach_count);
@@ -131,7 +149,6 @@ get_test_shmem_attach_count(PG_FUNCTION_ARGS)
 	PG_RETURN_INT32(TestShmem->attach_count);
 }
 
-
 /*
  * Callback for test_shmem_register().  test_shmem_register() provides the
  * options, we just pass them through to ShmemRequestStruct.
@@ -184,3 +201,17 @@ test_shmem_register(PG_FUNCTION_ARGS)
 
 	PG_RETURN_INT32(old_value);
 }
+
+/*
+ * Attempt to resize the fixed-size shared memory structure.  This should
+ * fail because the structure was not allocated with a maximum_size.
+ */
+PG_FUNCTION_INFO_V1(test_shmem_resize_fixed);
+Datum
+test_shmem_resize_fixed(PG_FUNCTION_ARGS)
+{
+	int32		new_size = PG_GETARG_INT32(0);
+
+	ShmemResizeStruct("test_shmem area", new_size);
+	PG_RETURN_VOID();
+}
diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out
index cf00b58fcbb..c3bdf3ae444 100644
--- a/src/test/regress/expected/rules.out
+++ b/src/test/regress/expected/rules.out
@@ -1770,8 +1770,11 @@ pg_shadow| SELECT pg_authid.rolname AS usename,
 pg_shmem_allocations| SELECT name,
     off,
     size,
-    allocated_size
-   FROM pg_get_shmem_allocations() pg_get_shmem_allocations(name, off, size, allocated_size);
+    allocated_size,
+    minimum_size,
+    maximum_size,
+    reserved_space
+   FROM pg_get_shmem_allocations() pg_get_shmem_allocations(name, off, size, allocated_size, minimum_size, maximum_size, reserved_space);
 pg_shmem_allocations_numa| SELECT name,
     numa_node,
     size
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 278b2f3194b..bb72513f2b5 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -3172,6 +3172,7 @@ TestDSMRegistryStruct
 TestDecodingData
 TestDecodingTxnData
 TestExtNode
+TestResizableShmemStruct
 TestShmemData
 TestSpec
 TestValueType
-- 
2.34.1

