Clean up NamedLWLockTranche stuff

Heikki Linnakangas <hlinnaka@iki.fi>

From: Heikki Linnakangas <hlinnaka@iki.fi>
To: Nathan Bossart <nathandbossart@gmail.com>, Robert Haas <robertmhaas@gmail.com>, "pgsql-hackers@postgresql.org" <pgsql-hackers@postgresql.org>
Date: 2026-03-26T12:16:52Z
Lists: pgsql-hackers

Attachments

While working on the new shmem allocation functions, I looked at how the 
NamedLWLockTranche stuff works now in lwlock.c, and I have to say it's a 
bit of a mess.

What is a "named tranche"? It usually means tranches requested with 
RequestNamedLWLockTranche() at postmaster startup. But all tranches have 
a name. LWLockTrancheNames includes all user-defined tranches, also ones 
assigned with LWLockNewTrancheId(), and MAX_NAMED_TRANCHES is the 
maximum for all of them.

At postmaster startup, NamedLWLockTrancheRequests points to a 
backend-private array. But after startup, and always in backends, it 
points to a copy in shared memory and 
LocalNamedLWLockTrancheRequestArray is used to hold the original. It 
took me a while to realize that NamedLWLockTrancheRequests in shared 
memory is *not* updated when you call LWLockNewTrancheId(), it only 
holds the requests made with RequestNamedLWLockTranche() before startup.

I propose the attached refactorings to make this less confusing. See 
commit messages for details.

- Heikki

Commits

  1. Fix outdated comment on MainLWLockArray

  2. Fix RequestNamedLWLockTranche in single-user mode

  3. Minor comment fixes to yesterday's LWLock tranche refactoring

  4. Move ShmemIndexLock into ShmemAllocator

  5. Use ShmemInitStruct to allocate lwlock.c's shared memory

  6. Use a separate spinlock to protect LWLockTranches

  7. Refactor how user-defined LWLock tranches are stored in shmem

  8. Rename MAX_NAMED_TRANCHES to MAX_USER_DEFINED_TRANCHES

  9. Fix re-initialization of LWLock-related shared memory.