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 <[email protected]> Author: Michael Paquier <[email protected]> Author: Colin McDonnell <[email protected]> Discussion: https://postgr.es/m/[email protected] Discussion: https://postgr.es/m/CALdYYtTg2x4nNLsjX99acjbQj=oto40cbxgdm1qzdzg7ubw...@mail.gmail.com Backpatch-through: 15 Branch ------ REL_16_STABLE Details ------- https://git.postgresql.org/pg/commitdiff/978888fafaccc4ebd404898004c828d18bcf121b Modified Files -------------- src/backend/utils/activity/pgstat.c | 28 ++++++----- src/backend/utils/activity/pgstat_shmem.c | 78 +++++++++++++++++++++---------- src/include/utils/pgstat_internal.h | 4 ++ 3 files changed, 74 insertions(+), 36 deletions(-)
