pgsql: Allocate pgstats entry body before insert into shared hashtable

Started by Michael Paquierabout 3 hours ago1 messagescommitters
Jump to latest
#1Michael Paquier
michael@paquier.xyz

Allocate pgstats entry body before insert into shared hashtable

8191e0c16a03 made pgstat_init_entry() return NULL on DSA allocation
failure so callers could delete a just-inserted hash entry. That works
when dsa_allocate_extended(DSA_ALLOC_NO_OOM) returns InvalidDsaPointer,
but not when the creation of a new DSM segment raises ERROR.

Under this type of failure, pgstat_init_entry() would mark the hash
entry live before allocating the body and cause an inconsistent state in
shared memory. The next backend trying to acquire the existing,
partially-initialized entry in pgstat_acquire_entry_ref() would crash,
taking down the server. Some of the public reports mentioned ENOSPC on
POSIX shared memory as one initial cause.

This commit refactors the pgstats entry initialization to happen in two
phases:
- Allocate the DSA chunk.
- Insert the hash entry with a valid segment.

If a concurrent insert wins, the allocation of the first phase needs an
extra set of dsa_free() calls (pulling back a DSM into its free list).

This change has been done on HEAD as of d9de60c5e47a, without a
backpatch as the API signature of pgstat_init_entry() has changed, and
is now backpatched following more complaints that this code leads to a
corrupted shared memory state, which is likely to crash a server at the
end. This backpatch guarantees ABI compatibility with a new
pgstat_init_entry_ext(), pgstat_init_entry() remaining as it is.

Colin has authored this part, while I have adjusted a few things to be
more consistent with HEAD. There are no more direct callers of
pgstat_init_entry() in all the stable branches. It is recommended that
out-of-core code adjusts to pgstat_init_entry_ext(), pgstat_init_entry()
should not be used when dealing with versions of Postgres up to v19.

Author: Yuriy Grigoryev <ju.grigorev@ftdata.ru>
Author: Michael Paquier <michael@paquier.xyz>
Author: Colin McDonnell <colinmcd94@gmail.com>
Discussion: /messages/by-id/ddc3ecfb01ce4e9698b23cc59767f016@localhost.localdomain
Discussion: /messages/by-id/CALdYYtTg2x4nNLsjX99acjbQj=oTo40CBXgDM1qzdzG7UbwzGQ@mail.gmail.com
Backpatch-through: 15

Branch
------
REL_19_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/20d6f4a22e552f458155bad000dc13ec046ba71c

Modified Files
--------------
src/backend/utils/activity/pgstat.c | 46 ++++++++++++------
src/backend/utils/activity/pgstat_shmem.c | 78 +++++++++++++++++++++----------
src/include/utils/pgstat_internal.h | 4 ++
3 files changed, 90 insertions(+), 38 deletions(-)