pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
[PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
13+ messages / 3 participants
[nested] [flat]

* [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-11 18:15  Alexandre Felipe <o.alexandre.felipe@gmail.com>
  0 siblings, 1 reply; 13+ messages in thread

From: Alexandre Felipe @ 2026-08-11 18:15 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

While reviewing another thread [1], I noticed a metion to lock duration,
and I think there is room to improve the current implementation on
InvalidateBuffer
and InvalidateVictimBuffer, that thread is already a fork of something else,
but I think this has its own merit.

In my (current) understanding partition LWLock guards a fraction of the
hash table
entries, and the buffer header lock as the name suggests guards the buffer
descriptor.

I think holding the Buffer header lock is not a problem,
as contention would require someone else accessing precisely that buffer,
holding the partition lock is more critical, as it may contend on thousands
of
distinct buffers.

This patch minimises the partition time, and keep the buffer header
guarding
the largest portion of the function body.

[1]
https://www.postgresql.org/message-id/dbbd1998-19ff-4ac2-b4b1-a39f4ec1b0f5%40iki.fi

Attachments:

0001-buffmgr-Tighten-LWLock-BuferMapping.patch (application/octet-stream, 5.2K) download From 77ee62fc25a4b92dd292a3ca25ff39840e1a2d3a Mon Sep 17 00:00:00 2001 From: Alexandre Felipe <o.alexandre.felipe@gmail.com> Date: Tue, 11 Aug 2026 18:53:55 +0100 Subject: [PATCH] buffmgr: Tighten LWLock:BuferMapping Previous implementation held buffer mapping partition lock for the nearly the duration of InvalidateBuffer and InvalidateVictimBuffer. This patch moves the lock/unlock closer to the BufTableDelete calls. This has a few advantages compared to the previous implementation 1. The partition lock is held for shorter time, specially if waiting for other backends to release the buffer. 2. Add a CHECK_FOR_INTERRUPTS, to improve responsiveness while waiting for other backends. 3. Simplifies the returning paths by not having to LWLockRelease in multiple locations. 4. (Unlikely) avoids unnecessary hash computation and locking when the buffer doesn't have to be deleted. --- src/backend/storage/buffer/bufmgr.c | 68 ++++++++++++----------------- 1 file changed, 27 insertions(+), 41 deletions(-) diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c index 169829eb020..8086d1d84c8 100644 --- a/src/backend/storage/buffer/bufmgr.c +++ b/src/backend/storage/buffer/bufmgr.c @@ -2370,31 +2370,14 @@ static void InvalidateBuffer(BufferDesc *buf) { BufferTag oldTag; - uint32 oldHash; /* hash value for oldTag */ - LWLock *oldPartitionLock; /* buffer partition lock for it */ - uint32 oldFlags; uint64 buf_state; /* Save the original buffer tag before dropping the spinlock */ oldTag = buf->tag; UnlockBufHdr(buf); - - /* - * Need to compute the old tag's hashcode and partition lock ID. XXX is it - * worth storing the hashcode in BufferDesc so we need not recompute it - * here? Probably not. - */ - oldHash = BufTableHashCode(&oldTag); - oldPartitionLock = BufMappingPartitionLock(oldHash); - retry: - /* - * Acquire exclusive mapping lock in preparation for changing the buffer's - * association. - */ - LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE); /* Re-lock the buffer header */ buf_state = LockBufHdr(buf); @@ -2403,7 +2386,6 @@ retry: if (!BufferTagsEqual(&buf->tag, &oldTag)) { UnlockBufHdr(buf); - LWLockRelease(oldPartitionLock); return; } @@ -2420,11 +2402,11 @@ retry: if (BUF_STATE_GET_REFCOUNT(buf_state) != 0) { UnlockBufHdr(buf); - LWLockRelease(oldPartitionLock); /* safety check: should definitely not be our *own* pin */ if (GetPrivateRefCount(BufferDescriptorGetBuffer(buf)) > 0) elog(ERROR, "buffer is pinned in InvalidateBuffer"); WaitIO(buf); + CHECK_FOR_INTERRUPTS(); goto retry; } @@ -2438,24 +2420,29 @@ retry: * Clear out the buffer's tag and flags. We must do this to ensure that * linear scans of the buffer array don't think the buffer is valid. */ - oldFlags = buf_state & BUF_FLAG_MASK; ClearBufferTag(&buf->tag); - UnlockBufHdrExt(buf, buf_state, - 0, - BUF_FLAG_MASK | BUF_USAGECOUNT_MASK, - 0); - /* * Remove the buffer from the lookup hashtable, if it was in there. */ - if (oldFlags & BM_TAG_VALID) + if (buf_state & BM_TAG_VALID) + { + /* + * Acquire exclusive lock on partition mapping only during the + * deletion process + */ + int32 oldHash = BufTableHashCode(&oldTag); + LWLock *partition_lock = BufMappingPartitionLock(oldHash); + + LWLockAcquire(partition_lock, LW_EXCLUSIVE); BufTableDelete(&oldTag, oldHash); + LWLockRelease(partition_lock); + } - /* - * Done with mapping lock. - */ - LWLockRelease(oldPartitionLock); + UnlockBufHdrExt(buf, buf_state, + 0, + BUF_FLAG_MASK | BUF_USAGECOUNT_MASK, + 0); } /* @@ -2480,11 +2467,6 @@ InvalidateVictimBuffer(BufferDesc *buf_hdr) /* have buffer pinned, so it's safe to read tag without lock */ tag = buf_hdr->tag; - hash = BufTableHashCode(&tag); - partition_lock = BufMappingPartitionLock(hash); - - LWLockAcquire(partition_lock, LW_EXCLUSIVE); - /* lock the buffer header */ buf_state = LockBufHdr(buf_hdr); @@ -2505,7 +2487,6 @@ InvalidateVictimBuffer(BufferDesc *buf_hdr) Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0); UnlockBufHdr(buf_hdr); - LWLockRelease(partition_lock); return false; } @@ -2515,7 +2496,6 @@ InvalidateVictimBuffer(BufferDesc *buf_hdr) * buffer, therefore BM_LOCK_WAKE_IN_PROGRESS should not be set. */ Assert(!(buf_state & BM_LOCK_WAKE_IN_PROGRESS)); - /* * Clear out the buffer's tag and flags and usagecount. This is not * strictly required, as BM_TAG_VALID/BM_VALID needs to be checked before @@ -2524,17 +2504,23 @@ InvalidateVictimBuffer(BufferDesc *buf_hdr) * tag (see e.g. FlushDatabaseBuffers()). */ ClearBufferTag(&buf_hdr->tag); - UnlockBufHdrExt(buf_hdr, buf_state, - 0, - BUF_FLAG_MASK | BUF_USAGECOUNT_MASK, - 0); Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0); /* finally delete buffer from the buffer mapping table */ + + hash = BufTableHashCode(&tag); + partition_lock = BufMappingPartitionLock(hash); + + LWLockAcquire(partition_lock, LW_EXCLUSIVE); + BufTableDelete(&tag, hash); LWLockRelease(partition_lock); + UnlockBufHdrExt(buf_hdr, buf_state, + 0, + BUF_FLAG_MASK | BUF_USAGECOUNT_MASK, + 0); buf_state = pg_atomic_read_u64(&buf_hdr->state); Assert(!(buf_state & (BM_DIRTY | BM_VALID | BM_TAG_VALID))); -- 2.53.0
^ permalink raw reply [nested|flat] 13+ messages in thread

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-11 18:47  Andres Freund <andres@anarazel.de>
  parent: Alexandre Felipe <o.alexandre.felipe@gmail.com>
  0 siblings, 1 reply; 13+ messages in thread

From: Andres Freund @ 2026-08-11 18:47 UTC (permalink / raw)
  To: Alexandre Felipe <o.alexandre.felipe@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2026-08-11 19:15:48 +0100, Alexandre Felipe wrote:
> While reviewing another thread [1], I noticed a metion to lock duration,
> and I think there is room to improve the current implementation on
> InvalidateBuffer
> and InvalidateVictimBuffer, that thread is already a fork of something else,
> but I think this has its own merit.
> 
> In my (current) understanding partition LWLock guards a fraction of the
> hash table
> entries, and the buffer header lock as the name suggests guards the buffer
> descriptor.

> I think holding the Buffer header lock is not a problem,
> as contention would require someone else accessing precisely that buffer,
> holding the partition lock is more critical, as it may contend on thousands
> of
> distinct buffers.
> 
> This patch minimises the partition time, and keep the buffer header
> guarding
> the largest portion of the function body.

You absolutely, definitely, never, ever ever may hold a spinlock over
something even remotely as complicated like an lwlock or a hashtable
delete. NEVER.

And without that the patch is completely unsafe.

Greetings,

Andres Freund





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

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-11 19:32  Alexandre Felipe <o.alexandre.felipe@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 13+ messages in thread

From: Alexandre Felipe @ 2026-08-11 19:32 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Aug 11, 2026, 20:26 Alexandre Felipe <o.alexandre.felipe@gmail.com>
wrote:

>
> On Tue, Aug 11, 2026 at 7:47 PM Andres Freund <andres@anarazel.de> wrote:
>
>> You absolutely, definitely, never, ever ever may hold a spinlock over
>> something even remotely as complicated like an lwlock or a hashtable
>> delete. NEVER.
>>
>
> So, the problem of spin locks there is that the contenders will spend
> CPU on this loop right?
> while (old_buf_state & BM_LOCKED)
> {
>   perform_spin_delay(&delayStatus);
>   old_buf_state = pg_atomic_read_u64(&desc->state);
> }
> And since there is a perform_spin_delay there I assume it is not 100%
> I imagined this was tuned to use maybe 1% CPU.
>
> If not, can't we simply use an exponentially increasing sleep until we get
> to say 1ms and that uses virtually 0 CPU while waiting.
>
>
>> And without that the patch is completely unsafe.
>>
>
> And with that is it safe? Pretending LockBufHdr not to be a spin-lock.
>
> Thank you for your quick response Andres
>
> Regards,
> Alexandre
>

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

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-11 20:57  Andres Freund <andres@anarazel.de>
  parent: Alexandre Felipe <o.alexandre.felipe@gmail.com>
  0 siblings, 1 reply; 13+ messages in thread

From: Andres Freund @ 2026-08-11 20:57 UTC (permalink / raw)
  To: Alexandre Felipe <o.alexandre.felipe@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2026-08-11 20:32:40 +0100, Alexandre Felipe wrote:
> On Tue, Aug 11, 2026, 20:26 Alexandre Felipe <o.alexandre.felipe@gmail.com>
> wrote:
> 
> >
> > On Tue, Aug 11, 2026 at 7:47 PM Andres Freund <andres@anarazel.de> wrote:
> >
> >> You absolutely, definitely, never, ever ever may hold a spinlock over
> >> something even remotely as complicated like an lwlock or a hashtable
> >> delete. NEVER.
> >>
> >
> > So, the problem of spin locks there is that the contenders will spend
> > CPU on this loop right?
> > while (old_buf_state & BM_LOCKED)
> > {
> >   perform_spin_delay(&delayStatus);
> >   old_buf_state = pg_atomic_read_u64(&desc->state);
> > }
> > And since there is a perform_spin_delay there I assume it is not 100%
> > I imagined this was tuned to use maybe 1% CPU.
> >
> > If not, can't we simply use an exponentially increasing sleep until we get
> > to say 1ms and that uses virtually 0 CPU while waiting.

It already uses exponential backoff, via perform_spin_delay().

I went into some detail why this is not ok in
https://postgr.es/m/bk5cbayf3q4yll4fqs2wbmonzhykg43k2k5v37vokkko53ebsd%40spcp4mxlb7hb

This specific change looks like it'd be flat out broken even without the
spinlock error recovery concerns, due to causing undetected deadlocks.  You
can't just change the nesting of locks in one place.

Greetings,

Andres Freund






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

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-16 09:54  Alexandre Felipe <o.alexandre.felipe@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 13+ messages in thread

From: Alexandre Felipe @ 2026-08-16 09:54 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Hackers,

Scrolling lwlock.c I noticed this piece of code in LWLockAttemptLock

 if (mode == LW_EXCLUSIVE)
 {
   lock_free = (old_state & LW_LOCK_MASK) == 0;
   if (lock_free)
     desired_state += LW_VAL_EXCLUSIVE;
 }
 else
 {
   lock_free = (old_state & LW_VAL_EXCLUSIVE) == 0;
   if (lock_free)
    desired_state += LW_VAL_SHARED;
 }

Where LW_LOCK_MASK is [xsss...ss], i.e. one bit for exclusive lock
followed by multiple bits for shared locks.

When acquiring shared locks LW_VAL_EXCLUSIVE times, we end up
with an exclusive lock because the shared lock count overflows to the
shared lock [0111...11] + [0000...01] = [1000..00].

That is probably fine, it will stop us from getting exclusive locks or any
additional shared locks.

The mode is stored as LW_SHARED
held_lwlocks[num_held_lwlocks++].mode = mode;

So the release will revert the counter correctly
   mode = held_lwlocks[i].mode;
   ...
   if (mode == LW_EXCLUSIVE)
    oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_EXCLUSIVE);
  else
    oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_SHARED);

But the LWLock state of LW_VAL_EXCLUSIVE shared locks is identical to
an LWLock with one exclusive lock.

I didn't see (so far) mentions of this (clever?) behaviour.
Is it undocumented feature, or something that should be fixed?

That would be a one line fix under the current assumptions
(old_state & LW_LOCK_MASK) + LW_VAL_SHARED < LW_VAL_EXCLUSIVE;

Regards,
Alexandre

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

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-24 07:22  Yuhang Qiu <iamqyh@gmail.com>
  parent: Alexandre Felipe <o.alexandre.felipe@gmail.com>
  0 siblings, 1 reply; 13+ messages in thread

From: Yuhang Qiu @ 2026-08-24 07:22 UTC (permalink / raw)
  To: Alexandre Felipe <o.alexandre.felipe@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

> Is it undocumented feature, or something that should be fixed?


```C
#define MAX_BACKENDS_BITS 18
#define MAX_BACKENDS ((1U << MAX_BACKENDS_BITS)-1)

/* assumes MAX_BACKENDS is a (power of 2) - 1, checked below */
#define LW_VAL_EXCLUSIVE (MAX_BACKENDS + 1)
#define LW_VAL_SHARED 1

/* already (power of 2)-1, i.e. suitable for a mask */
#define LW_SHARED_MASK MAX_BACKENDS
#define LW_LOCK_MASK (MAX_BACKENDS | LW_VAL_EXCLUSIVE)
```

It's documented, not very prominently - see the lwlock.c file header.
LW_VAL_EXCLUSIVE is MAX_BACKENDS + 1, so overflowing needs MAX_BACKENDS + 1
shared holders, and InitializeMaxBackends() won't let MaxBackends get that big.

So there's nothing to fix here.

Best Regards,
Yuhang Qiu.






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

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-24 08:16  Alexandre Felipe <o.alexandre.felipe@gmail.com>
  parent: Yuhang Qiu <iamqyh@gmail.com>
  0 siblings, 1 reply; 13+ messages in thread

From: Alexandre Felipe @ 2026-08-24 08:16 UTC (permalink / raw)
  To: Yuhang Qiu <iamqyh@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Thank you Yuhang,

That is correct under the (very reasonable) assumption that a backend will
not hold more than one shared lock of the LWLock.

I also studied the current LWLock the implementation and there is room to
make the no-contention path faster. Is that something worth doing,
or is it pointless?

Regards,
Alexandre


On Mon, Aug 24, 2026 at 8:23 AM Yuhang Qiu <iamqyh@gmail.com> wrote:

> > Is it undocumented feature, or something that should be fixed?
>
>
> ```C
> #define MAX_BACKENDS_BITS 18
> #define MAX_BACKENDS ((1U << MAX_BACKENDS_BITS)-1)
>
> /* assumes MAX_BACKENDS is a (power of 2) - 1, checked below */
> #define LW_VAL_EXCLUSIVE (MAX_BACKENDS + 1)
> #define LW_VAL_SHARED 1
>
> /* already (power of 2)-1, i.e. suitable for a mask */
> #define LW_SHARED_MASK MAX_BACKENDS
> #define LW_LOCK_MASK (MAX_BACKENDS | LW_VAL_EXCLUSIVE)
> ```
>
> It's documented, not very prominently - see the lwlock.c file header.
> LW_VAL_EXCLUSIVE is MAX_BACKENDS + 1, so overflowing needs MAX_BACKENDS + 1
> shared holders, and InitializeMaxBackends() won't let MaxBackends get that
> big.
>
> So there's nothing to fix here.
>
> Best Regards,
> Yuhang Qiu.
>
>

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

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-24 12:25  Andres Freund <andres@anarazel.de>
  parent: Alexandre Felipe <o.alexandre.felipe@gmail.com>
  0 siblings, 1 reply; 13+ messages in thread

From: Andres Freund @ 2026-08-24 12:25 UTC (permalink / raw)
  To: Alexandre Felipe <o.alexandre.felipe@gmail.com>; +Cc: Yuhang Qiu <iamqyh@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

Please don't top-quote.

On 2026-08-24 09:16:28 +0100, Alexandre Felipe wrote:
> I also studied the current LWLock the implementation and there is room to
> make the no-contention path faster. Is that something worth doing,
> or is it pointless?

Hard to say without knowing what you're actually going to propose. Of couse
making the uncontended path faster is attractive, but correctness / complexity
/ contended performance all are also not uninmportant.

Greetings,

Andres Freund





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

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-24 21:01  Alexandre Felipe <o.alexandre.felipe@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 2 replies; 13+ messages in thread

From: Alexandre Felipe @ 2026-08-24 21:01 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Yuhang Qiu <iamqyh@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Mon, Aug 24, 2026 at 1:25 PM Andres Freund <andres@anarazel.de> wrote:

> On 2026-08-24 09:16:28 +0100, Alexandre Felipe wrote:
> > I also studied the current LWLock the implementation and there is room to
> > make the no-contention path faster. Is that something worth doing,
> > or is it pointless?
>
> Hard to say without knowing what you're actually going to propose. Of couse
> making the uncontended path faster is attractive, but correctness /
> complexity
> / contended performance all are also not uninmportant.
>

Here I include the experiments. Maybe you don't want to use this
implementation
but it might give you some hints to write a faster version that you like.

There are no algorithmic changes. The changes are about

0002 having two distinct paths for LW_EXCLUSIVE and LW_SHARED,
the rest is diminishing returns. And also added LWLockReleaseLast,
added wrappers as inline functions in lwlock.h that compiles the
current code base replacing the calls
LWLockAcquire(lock, LW_EXCLUSIVE | LW_SHARED) by the
LWLockAcquire(Exclusive|Shared)(lock)



0003 reading the mode from the LWLock state and saving space and time
storing it in the held lwlocks array.
0004 well, bring LWLock(Acquire/Release)X external functions that take
mode as a parameter (a baseline).
0005 Inlined LWLockAttemptLock and folded the loop, placing a single
LWLockAttemptLock at the top of the loop followed by the common logic
(previously at the end bottom of the function), then enqueue and continue
or wait.

Regards,
Alexandre

Attachments: download all (5 files, .tar.gz)

0002-LWLock-fast-paths.patch (application/octet-stream, 12.4K) download From 139f5d67266c94f96f3e88b056c297307efacb32 Mon Sep 17 00:00:00 2001 From: Alexandre Felipe <o.alexandre.felipe@gmail.com> Date: Mon, 17 Aug 2026 18:41:39 +0100 Subject: [PATCH 2/5] LWLock fast paths inline LWLockAcquire(LWLock* , LWLockMode) +- extern LWLockAcquireShared(LWLock*) | +- fast LWLockAcquireCommon(LWLock*, LW_SHARED) | +- fast LWLockAttemptLock(LWLock*, LW_SHARED) | +- ... slow path +- extern LWLockACquireExclusive(LWLock*) +- fast LWLockAcquireCommon(LWLock*, LW_EXCLUSIVE) +- fast LWLockAttemptLock(LWLock*, LW_EXCLUSIVE) +- ... slow path LWLock tracking only stores (LWLock*), the mode can be inferred at any time from the LWLock state. since at any time either the number of exclusive locks or the number of shared locks on a LWLock must be zero. If a lock is currently held, one of them will be non-zero. Is reading the mode from the lock state in the hot path a concern? This patch provides a LWLockRelease(LWLock, LWLockMode) that uses an architecture similar to LWLockAcquire. inline LWLockReleaseMode(LWLock* , LWLockMode) +- extern LWLockReleaseShared(LWLock*) | +- if(lock is at the top of held_lwlocks) | | fast LWLockReleaseCommon(LWLock*, LW_SHARED) | +- ... slow path +- extern LWLockReleaseExclusive(LWLock*) +- if(lock is at the top of held_lwlocks) | fast LWLockReleaseCommon(LWLock*, LW_EXCLUSIVE) +- ... slow path Is the top of the stack check in the hot path a concern? This patch provides a LWLockReleaseLast(LWLock*, LWLockMode), that only checks for the existence of a lock. inline LWLockReleaseMode(LWLock* , LWLockMode) +- extern LWLockReleaseShared(LWLock*) | +- fast LWLockReleaseCommon(LWLock*, LW_SHARED) +- extern LWLockReleaseExclusive(LWLock*) +- fast LWLockReleaseCommon(LWLock*, LW_EXCLUSIVE) But this can easily be removed if it raises safety concerns. Example results ==> running lwlock/query.sql (n=128 rounds=1000000) Output format is aligned. op | avg | min | q1 | med | q3 | max | std -------------+-------+------+-------+-------+-------+--------+------ spin-lock | 14.75 | 7.81 | 12.70 | 15.63 | 16.28 | 68.69 | 4.28 LWLock-ex | 6.96 | 5.86 | 6.51 | 6.52 | 6.84 | 93.75 | 3.98 LWLock-sh | 6.86 | 5.86 | 6.19 | 6.52 | 6.84 | 130.21 | 4.01 lw-ex-mode | 6.82 | 5.86 | 6.19 | 6.51 | 6.84 | 103.20 | 3.95 lw-ex-last | 6.77 | 5.86 | 6.19 | 6.51 | 6.84 | 116.53 | 3.65 lw-sh-mode | 6.69 | 5.86 | 6.19 | 6.51 | 6.84 | 29.95 | 1.41 lw-sh-last | 6.96 | 5.86 | 6.19 | 6.51 | 6.84 | 320.96 | 9.98 LWLock-cond | 6.01 | 5.20 | 5.53 | 5.86 | 5.86 | 17.25 | 1.04 nop | 0.54 | 0.00 | 0.33 | 0.33 | 0.66 | 2.93 | 0.30 --- src/backend/storage/lmgr/lwlock.c | 233 +++++++++++++++++---- src/include/storage/lwlock.h | 34 ++- src/test/modules/microbench/lwlock/bench.c | 36 ++++ 3 files changed, 262 insertions(+), 41 deletions(-) diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c index 82a1d4d2e26..f572b4a4f84 100644 --- a/src/backend/storage/lmgr/lwlock.c +++ b/src/backend/storage/lmgr/lwlock.c @@ -1146,8 +1146,8 @@ LWLockDequeueSelf(LWLock *lock) * * Side effect: cancel/die interrupts are held off until lock release. */ -bool -LWLockAcquire(LWLock *lock, LWLockMode mode) +static pg_always_inline bool +LWLockAcquireCommon(LWLock *lock, LWLockMode mode) { PGPROC *proc = MyProc; bool result = true; @@ -1310,6 +1310,30 @@ LWLockAcquire(LWLock *lock, LWLockMode mode) return result; } +/* + * LWLockAcquireExclusive - acquire an exclusive lock + * + * extern function specialised for LW_SHARED at compile time + * can be called via LWLockAcquire(lock, LW_EXCLUSIVE) + */ +extern bool +LWLockAcquireExclusive(LWLock *lock) +{ + return LWLockAcquireCommon(lock, LW_EXCLUSIVE); +} + +/* + * LWLockAcquireShared - acquire a shared lock + * + * Extern function specialised for LW_SHARED at compile time. + * can be called via LWLockAcquire(lock, LW_SHARED) + */ +extern bool +LWLockAcquireShared(LWLock *lock) +{ + return LWLockAcquireCommon(lock, LW_SHARED); +} + /* * LWLockConditionalAcquire - acquire a lightweight lock in the specified mode * @@ -1757,36 +1781,28 @@ LWLockUpdateVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 val) /* - * LWLockRelease - release a previously acquired lock + * Cold path for waking waiters - kept out of line to enable shrink-wrapping. + */ +static pg_noinline void +LWLockReleaseWakeWaiters(LWLock *lock) +{ + /* XXX: remove before commit? */ + LOG_LWDEBUG("LWLockRelease", lock, "releasing waiters"); + LWLockWakeup(lock); + RESUME_INTERRUPTS(); +} + +/* + * LWLockReleaseInternal - core release logic, always inlined for constant folding. * * NB: This will leave lock->owner pointing to the current backend (if * LOCK_DEBUG is set). This is somewhat intentional, as it makes it easier to * debug cases of missing wakeups during lock release. */ -void -LWLockRelease(LWLock *lock) +static pg_always_inline void +LWLockReleaseInternal(LWLock *lock, LWLockMode mode) { - LWLockMode mode; uint32 oldstate; - bool check_waiters; - int i; - - /* - * Remove lock from list of locks held. Usually, but not always, it will - * be the latest-acquired lock; so search array backwards. - */ - for (i = num_held_lwlocks; --i >= 0;) - if (lock == held_lwlocks[i].lock) - break; - - if (i < 0) - elog(ERROR, "lock %s is not held", T_NAME(lock)); - - mode = held_lwlocks[i].mode; - - num_held_lwlocks--; - for (; i < num_held_lwlocks; i++) - held_lwlocks[i] = held_lwlocks[i + 1]; PRINT_LWDEBUG("LWLockRelease", lock, mode); @@ -1807,30 +1823,167 @@ LWLockRelease(LWLock *lock) /* * Check if we're still waiting for backends to get scheduled, if so, - * don't wake them up again. + * don't wake them up again. As waking up waiters requires the spinlock + * to be acquired, only do so if necessary. */ - if ((oldstate & LW_FLAG_HAS_WAITERS) && - !(oldstate & LW_FLAG_WAKE_IN_PROGRESS) && - (oldstate & LW_LOCK_MASK) == 0) - check_waiters = true; - else - check_waiters = false; + if (unlikely((oldstate & LW_FLAG_HAS_WAITERS) && + !(oldstate & LW_FLAG_WAKE_IN_PROGRESS) && + (oldstate & LW_LOCK_MASK) == 0)) + { + LWLockReleaseWakeWaiters(lock); + return; + } + + /* + * Now okay to allow cancel/die interrupts. + */ + RESUME_INTERRUPTS(); +} + +/* + * LWLockRelease - generic lock release + * + * extern function without compile-time mode specialisation + */ +extern void +LWLockRelease(LWLock *lock) +{ + int i = num_held_lwlocks - 1; + LWLockMode mode; /* - * As waking up waiters requires the spinlock to be acquired, only do so - * if necessary. + * Fast path: check if this is the most recently acquired lock. */ - if (check_waiters) + if (likely(i >= 0 && held_lwlocks[i].lock == lock)) { - /* XXX: remove before commit? */ - LOG_LWDEBUG("LWLockRelease", lock, "releasing waiters"); - LWLockWakeup(lock); + mode = held_lwlocks[i].mode; + num_held_lwlocks = i; + LWLockReleaseInternal(lock, mode); + return; } /* - * Now okay to allow cancel/die interrupts. + * Slow path: search array backwards to find the lock. */ - RESUME_INTERRUPTS(); + + for (i = num_held_lwlocks; --i >= 0;) + if (lock == held_lwlocks[i].lock) + break; + + if (i < 0) + elog(ERROR, "lock %s is not held", T_NAME(lock)); + + mode = held_lwlocks[i].mode; + + num_held_lwlocks--; + for (; i < num_held_lwlocks; i++) + held_lwlocks[i] = held_lwlocks[i + 1]; + + LWLockReleaseInternal(lock, mode); +} + +/* + * LWLockReleaseCommon - release a lock with known mode + * + * Potentially faster than LWLockRelease, doesn't have to + * read the mode and logic can be simplified if passed mode + * is a compile time constant. + * + * Inlined in LWLockReleaseExclusive and LWLockRelelaseShared + */ +static pg_always_inline void +LWLockReleaseCommon(LWLock *lock, LWLockMode mode) +{ + int i = num_held_lwlocks - 1; + + if (likely(i >= 0 && held_lwlocks[i].lock == lock)) + { + Assert(held_lwlocks[i].mode == mode); + num_held_lwlocks = i; + LWLockReleaseInternal(lock, mode); + return; + } + + + for (;i >= 0; --i) + if (lock == held_lwlocks[i].lock) + break; + + if (i < 0) + elog(ERROR, "lock %s is not held", T_NAME(lock)); + + Assert(held_lwlocks[i].mode == mode); + + num_held_lwlocks--; + for (; i < num_held_lwlocks; i++) + held_lwlocks[i] = held_lwlocks[i + 1]; + + LWLockReleaseInternal(lock, mode); +} +/* + * LWLockReleaseExclusive + * + * Extern function specialised for LW_EXCLUSIVE at compile time + * Can be called via LWLockReleaseMode(LW_EXCLUSIVE) + */ +extern void +LWLockReleaseExclusive(LWLock *lock) +{ + LWLockReleaseCommon(lock, LW_EXCLUSIVE); +} + +/* + * LWLockReleaseShared + * + * Extern function specialised for LW_SHARED at compile time + * Can be called via LWLockReleaseMode(LW_SHARED) + */ +extern void +LWLockReleaseShared(LWLock *lock) +{ + LWLockReleaseCommon(lock, LW_SHARED); +} + + +/* + * LWLockReleaseLastCommon - release a lock at the top of the stack + * + * Static function to be inlined in LWLockReleaseLastShared + * and LWLockReleaseLastExclusive by the compiler. + */ +static pg_always_inline void +LWLockReleaseLastCommon(LWLock *lock, LWLockMode mode) +{ + Assert(num_held_lwlocks > 0); + Assert(held_lwlocks[num_held_lwlocks - 1].lock == lock); + Assert(held_lwlocks[num_held_lwlocks - 1].mode == mode); + + num_held_lwlocks--; + LWLockReleaseInternal(lock, mode); +} + +/* + * LWLockReleaseLastExclusive: + * + * extern function specialised for LW_EXCLUSIVE mode at compile time + * Can be called via LWLockReleaseLast(LW_EXCLUSIVE) + */ +extern void +LWLockReleaseLastExclusive(LWLock *lock) +{ + LWLockReleaseLastCommon(lock, LW_EXCLUSIVE); +} + +/* + * LWLockReleaseLastShared: LW_SHARED mode LWLock release + * + * extern function specialized for LW_SHARED mode at compile time + * Can be called via LWLockReleaseLast(LW_EXCLUSIVE) + */ +extern void +LWLockReleaseLastShared(LWLock *lock) +{ + LWLockReleaseLastCommon(lock, LW_SHARED); } /* diff --git a/src/include/storage/lwlock.h b/src/include/storage/lwlock.h index efa5b427e9f..aa113b7ddb2 100644 --- a/src/include/storage/lwlock.h +++ b/src/include/storage/lwlock.h @@ -113,10 +113,42 @@ typedef enum LWLockMode extern PGDLLIMPORT bool Trace_lwlocks; #endif -extern bool LWLockAcquire(LWLock *lock, LWLockMode mode); +extern bool LWLockAcquireExclusive(LWLock *lock); +extern bool LWLockAcquireShared(LWLock *lock); + +inline bool LWLockAcquire(LWLock *lock, LWLockMode mode) +{ + if(mode == LW_EXCLUSIVE) + return LWLockAcquireExclusive(lock); + else + return LWLockAcquireShared(lock); +} + extern bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode); extern bool LWLockAcquireOrWait(LWLock *lock, LWLockMode mode); extern void LWLockRelease(LWLock *lock); + +extern void LWLockReleaseExclusive(LWLock *lock); +extern void LWLockReleaseShared(LWLock *lock); +inline void LWLockReleaseMode(LWLock *lock, LWLockMode mode) +{ + if(mode == LW_EXCLUSIVE) + LWLockReleaseExclusive(lock); + else + LWLockReleaseShared(lock); +} + +extern void LWLockReleaseLastExclusive(LWLock *lock); +extern void LWLockReleaseLastShared(LWLock *lock); +inline void LWLockReleaseLast(LWLock *lock, LWLockMode mode) +{ + if(mode == LW_EXCLUSIVE) + LWLockReleaseLastExclusive(lock); + else + LWLockReleaseLastShared(lock); +} + + extern void LWLockReleaseClearVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 val); extern void LWLockReleaseAll(void); extern bool LWLockHeldByMe(LWLock *lock); diff --git a/src/test/modules/microbench/lwlock/bench.c b/src/test/modules/microbench/lwlock/bench.c index 33d75770a0d..d15939801d7 100644 --- a/src/test/modules/microbench/lwlock/bench.c +++ b/src/test/modules/microbench/lwlock/bench.c @@ -99,6 +99,42 @@ bench_lwlock(PG_FUNCTION_ARGS) } END_TIMING; + BEGIN_TIMING("lw-ex-mode", n) + { + LWLock *lock = locks[i]; + + LWLockAcquire(lock, LW_EXCLUSIVE); + LWLockReleaseMode(lock, LW_EXCLUSIVE); + } + END_TIMING; + + BEGIN_TIMING("lw-ex-last", n) + { + LWLock *lock = locks[i]; + + LWLockAcquire(lock, LW_EXCLUSIVE); + LWLockReleaseLast(lock, LW_EXCLUSIVE); + } + END_TIMING; + + BEGIN_TIMING("lw-sh-mode", n) + { + LWLock *lock = locks[i]; + + LWLockAcquire(lock, LW_SHARED); + LWLockReleaseMode(lock, LW_SHARED); + } + END_TIMING; + + BEGIN_TIMING("lw-sh-last", n) + { + LWLock *lock = locks[i]; + + LWLockAcquire(lock, LW_SHARED); + LWLockReleaseLast(lock, LW_SHARED); + } + END_TIMING; + BEGIN_TIMING("LWLock-cond", n) { LWLock *lock = locks[i]; -- 2.53.0
0004-mode-as-a-dynamic-parameter.patch (application/octet-stream, 3.2K) download From a7e12772e3414d71e491647f46a8efffda1e88af Mon Sep 17 00:00:00 2001 From: Alexandre Felipe <o.alexandre.felipe@gmail.com> Date: Mon, 24 Aug 2026 20:48:09 +0100 Subject: [PATCH 4/5] mode as a dynamic parameter Just to check the impact the branches in the code. Passing the mode as a variable, to the same implementation makes it about 50% (on one machine). op | avg | min | q1 | med | q3 | max | std ----------------+-------+------+-------+-------+-------+--------+------ spin-lock | 13.89 | 7.49 | 12.04 | 15.30 | 15.95 | 23.11 | 3.26 LWLock-ex | 6.50 | 5.53 | 6.19 | 6.19 | 6.51 | 26.37 | 0.85 LWLock-sh | 6.48 | 5.86 | 6.19 | 6.19 | 6.52 | 10.74 | 0.58 LWLock-dynmode | 9.47 | 7.81 | 9.11 | 9.44 | 9.77 | 14.65 | 0.96 lw-ex-mode | 9.39 | 8.46 | 8.79 | 9.12 | 9.44 | 117.51 | 3.82 lw-ex-last | 6.16 | 5.53 | 5.86 | 6.18 | 6.19 | 9.11 | 0.54 lw-sh-mode | 9.22 | 8.46 | 8.79 | 9.12 | 9.44 | 13.67 | 0.83 lw-sh-last | 6.09 | 5.53 | 5.86 | 5.86 | 6.19 | 19.20 | 0.68 LWLock-cond | 6.01 | 5.20 | 5.53 | 5.86 | 6.51 | 10.09 | 0.68 nop | 0.84 | 0.32 | 0.65 | 0.98 | 0.98 | 2.28 | 0.20 --- src/backend/storage/lmgr/lwlock.c | 12 +++++++++++- src/include/storage/lwlock.h | 2 ++ src/test/modules/microbench/lwlock/bench.c | 10 ++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c index 444b5ed37ec..00b589f158e 100644 --- a/src/backend/storage/lmgr/lwlock.c +++ b/src/backend/storage/lmgr/lwlock.c @@ -1308,7 +1308,10 @@ LWLockAcquireCommon(LWLock *lock, LWLockMode mode) return result; } - +bool LWLockAcquireX(LWLock *lock, LWLockMode mode) +{ + return LWLockAcquireCommon(lock, mode); +} /* * LWLockAcquireExclusive - acquire an exclusive lock * @@ -1914,6 +1917,13 @@ LWLockReleaseCommon(LWLock *lock, LWLockMode mode) LWLockReleaseInternal(lock, mode); } + +extern void +LWLockReleaseX(LWLock *lock, LWLockMode mode) +{ + LWLockReleaseCommon(lock, mode); +} + /* * LWLockReleaseExclusive * diff --git a/src/include/storage/lwlock.h b/src/include/storage/lwlock.h index aa113b7ddb2..dec4119d638 100644 --- a/src/include/storage/lwlock.h +++ b/src/include/storage/lwlock.h @@ -123,6 +123,8 @@ inline bool LWLockAcquire(LWLock *lock, LWLockMode mode) else return LWLockAcquireShared(lock); } +bool LWLockAcquireX(LWLock *lock, LWLockMode mode); +void LWLockReleaseX(LWLock *lock, LWLockMode mode); extern bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode); extern bool LWLockAcquireOrWait(LWLock *lock, LWLockMode mode); diff --git a/src/test/modules/microbench/lwlock/bench.c b/src/test/modules/microbench/lwlock/bench.c index d15939801d7..93d2e52c254 100644 --- a/src/test/modules/microbench/lwlock/bench.c +++ b/src/test/modules/microbench/lwlock/bench.c @@ -99,6 +99,16 @@ bench_lwlock(PG_FUNCTION_ARGS) } END_TIMING; + + BEGIN_TIMING("LWLock-X", n) + { + LWLock *lock = locks[i]; + + LWLockAcquireX(lock, LW_SHARED); + LWLockReleaseX(lock, LW_SHARED); + } + END_TIMING; + BEGIN_TIMING("lw-ex-mode", n) { LWLock *lock = locks[i]; -- 2.53.0
0001-Benchmark.patch (application/octet-stream, 18.0K) download From 7e2fe005525d59c4def5ac0f1060d3d4bfa43351 Mon Sep 17 00:00:00 2001 From: Alexandre Felipe <o.alexandre.felipe@gmail.com> Date: Mon, 17 Aug 2026 18:19:43 +0100 Subject: [PATCH 1/5] Benchmark This adds a module for benchmarking LWLocks in a tight loop. This time I am structuring the benchmark module as a generic one that could be extended in the future. The idea is that under the module microbench a contributor that trying to do a low level benchmark could write a new component there and easily get pooled measurements exposed via SQL. microbench-head-1.0.sql implements a standard processing helping to understand not only the average performance but also rank statistics. e.g. op | avg | min | [q1 | med | q3] | max | std -------------+-------+------+------+------+------+-------+------ spin-lock | 10.07 | 9.11 | 9.77 | 9.77 | 9.77 | 19.21 | 1.20 LWLock-ex | 8.26 | 7.16 | 7.81 | 8.13 | 8.14 | 17.25 | 0.74 LWLock-sh | 8.18 | 7.16 | 7.81 | 7.81 | 8.14 | 10.74 | 0.72 LWLock-cond | 6.81 | 6.18 | 6.84 | 6.84 | 6.84 | 34.18 | 0.95 nop | 1.00 | 0.32 | 0.98 | 0.98 | 0.98 | 1.95 | 0.11 (5 rows) In this particular exmaple, spin-lock is the LockBufHdr and UnlockBufHdr, LWLock-ex and LWLock-sh represents LWLockAcquire followed by LWLockRelease, in exclusive and shared mode, respectively. LWLock-cond is a conditional shared lock followed by a LWLockRelease. nop is just reading the lwlock pointer in the loop and gives a baseline. Where statistics of average times of each measurement are computed as follows: avg: average time per min: above 0% of the data (obviously) q1: end of first quartile, above 25% med: short for median, above 50% q2: end of third quartile, above 75% max: above 100% of the data (obviously) std: standard deviation, measures how dispersed is the data. To reduce the impact of the time measurement itself one can repeat the operation a large number of times in a loop between two timer observations. One looses the individual measurements but the averages are still going to reflect to some extent the variability of the operation itself. --- src/test/modules/microbench/Makefile | 61 ++++++++ src/test/modules/microbench/lwlock/bench.c | 123 ++++++++++++++++ .../modules/microbench/lwlock/install.sql | 10 ++ src/test/modules/microbench/lwlock/query.sql | 8 ++ src/test/modules/microbench/meson.build | 33 +++++ .../microbench/microbench-head--1.0.sql | 44 ++++++ .../modules/microbench/microbench.control | 4 + src/test/modules/microbench/randomize.h | 23 +++ .../modules/microbench/scripts/run-test.sh | 135 ++++++++++++++++++ src/test/modules/microbench/timing-magic.h | 30 ++++ 10 files changed, 471 insertions(+) create mode 100644 src/test/modules/microbench/Makefile create mode 100644 src/test/modules/microbench/lwlock/bench.c create mode 100644 src/test/modules/microbench/lwlock/install.sql create mode 100644 src/test/modules/microbench/lwlock/query.sql create mode 100644 src/test/modules/microbench/meson.build create mode 100644 src/test/modules/microbench/microbench-head--1.0.sql create mode 100644 src/test/modules/microbench/microbench.control create mode 100644 src/test/modules/microbench/randomize.h create mode 100755 src/test/modules/microbench/scripts/run-test.sh create mode 100644 src/test/modules/microbench/timing-magic.h diff --git a/src/test/modules/microbench/Makefile b/src/test/modules/microbench/Makefile new file mode 100644 index 00000000000..4cdbe4ff0c7 --- /dev/null +++ b/src/test/modules/microbench/Makefile @@ -0,0 +1,61 @@ +# src/test/modules/microbench/Makefile + +PGFILEDESC = "microbench - suite of functions for micro-benchmarks" + +EXTENSION = microbench +MODULE_big = microbench + +# One subdir per benchmark: <name>/bench.c, <name>/install.sql, <name>/query.sql +MICROBENCH_TESTS := $(sort $(patsubst %/bench.c,%,$(wildcard */bench.c))) +SQL_FRAGMENTS := $(addsuffix /install.sql,$(MICROBENCH_TESTS)) + +MICROBENCH_SQL_HEAD = microbench-head--1.0.sql +MICROBENCH_SQL_BUILT = microbench--1.0.sql + +OBJS = \ + $(WIN32RES) \ + $(addsuffix /bench.o,$(MICROBENCH_TESTS)) + +# Generated extension script; must be DATA_built so all/install depend on it. +DATA_built = $(MICROBENCH_SQL_BUILT) + +ifdef USE_PGXS +PG_CONFIG = pg_config +PGXS := $(shell $(PG_CONFIG) --pgxs) +include $(PGXS) +else +subdir = src/test/modules/microbench +top_builddir = ../../../.. +include $(top_builddir)/src/Makefile.global +include $(top_srcdir)/contrib/contrib-global.mk + +# Link the module against an explicit postgres binary when requested, e.g. +# make install MICROBENCH_POSTGRES=/path/to/bin/postgres +ifdef MICROBENCH_POSTGRES +BE_DLLLIBS := -bundle_loader $(MICROBENCH_POSTGRES) +endif +endif + +$(MICROBENCH_SQL_BUILT): $(addprefix $(srcdir)/,$(MICROBENCH_SQL_HEAD)) \ + $(addprefix $(srcdir)/,$(SQL_FRAGMENTS)) + cat $^ > $@ + +# Incremental compile of a single benchmark folder, e.g. make lwlock +$(MICROBENCH_TESTS): %: %/bench.o + +%/bench.o: %/bench.c randomize.h timing-magic.h + $(COMPILE.c) -I. -o $@ $< + +.PHONY: run tests list $(MICROBENCH_TESTS) + +tests: $(MICROBENCH_TESTS) + +list: + @echo $(MICROBENCH_TESTS) + +run: +ifndef TEST + $(error TEST is required, e.g. make run TEST=lwlock) +endif + @test -d '$(TEST)' || (echo "unknown test: $(TEST)" && exit 1) + $(SHELL) '$(srcdir)/scripts/run-test.sh' '$(TEST)' diff --git a/src/test/modules/microbench/lwlock/bench.c b/src/test/modules/microbench/lwlock/bench.c new file mode 100644 index 00000000000..33d75770a0d --- /dev/null +++ b/src/test/modules/microbench/lwlock/bench.c @@ -0,0 +1,123 @@ +/*------------------------------------------------------------------------- + * + * lwlock/bench.c + * Micro-benchmark of LWLock acquire/release paths. + * + * IDENTIFICATION + * src/test/modules/microbench/lwlock/bench.c + * + *------------------------------------------------------------------------- + */ +#include "postgres.h" + +#include "fmgr.h" +#include "funcapi.h" +#include "portability/instr_time.h" +#include "storage/buf_internals.h" +#include "storage/lwlock.h" +#include "utils/builtins.h" +#include "utils/tuplestore.h" + +#include "randomize.h" +#include "timing-magic.h" + +PG_MODULE_MAGIC; + +PG_FUNCTION_INFO_V1(bench_lwlock); + +/* + * bench_lwlock(n, rounds, randomize) -> SETOF + * (op text, avg_ns float8, batch_size int8, id int8) + */ +Datum +bench_lwlock(PG_FUNCTION_ARGS) +{ + int64 n = PG_GETARG_INT64(0); + int64 rounds = PG_ARGISNULL(1) ? 1 : PG_GETARG_INT64(1); + bool randomize = PG_ARGISNULL(2) ? true : PG_GETARG_BOOL(2); + ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo; + LWLock **locks; + volatile int64 sink PG_USED_FOR_ASSERTS_ONLY = 0; + + if (n <= 0 || rounds <= 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("n and rounds must be positive"))); + + if (n > NUM_BUFFER_PARTITIONS) + n = NUM_BUFFER_PARTITIONS; + + InitMaterializedSRF(fcinfo, 0); + + locks = palloc(sizeof(LWLock *) * n); + if (randomize) + { + pg_prng_state rng; + + pg_prng_seed(&rng, 0xDA7ABA5E); + for (int i = 0; i < n; i++) + locks[i] = BufMappingPartitionLock(i); + shuffle_pointers(&rng, (void **) locks, (int) n); + } + else + { + for (int i = 0; i < n; i++) + locks[i] = BufMappingPartitionLock(0); + } + + if (!timing_initialized) + pg_initialize_timing(); + + for (int64 r = 0; r < rounds; r++) + { + INIT_TIMING_SCOPE(); + { + BufferDesc *buf_desc = GetBufferDescriptor(1); + BEGIN_TIMING("spin-lock", n) + { + LockBufHdr(buf_desc); + UnlockBufHdr(buf_desc); + } + END_TIMING; + } + + BEGIN_TIMING("LWLock-ex", n) + { + LWLock *lock = locks[i]; + + LWLockAcquire(lock, LW_EXCLUSIVE); + LWLockRelease(lock); + } + END_TIMING; + + BEGIN_TIMING("LWLock-sh", n) + { + LWLock *lock = locks[i]; + + LWLockAcquire(lock, LW_SHARED); + LWLockRelease(lock); + } + END_TIMING; + + BEGIN_TIMING("LWLock-cond", n) + { + LWLock *lock = locks[i]; + + if (!LWLockConditionalAcquire(lock, LW_SHARED)) + elog(ERROR, "Failed to acquire lock"); + LWLockRelease(lock); + } + END_TIMING; + + BEGIN_TIMING("nop", n) + { + LWLock *lock = locks[i]; + + sink += (int64) (uintptr_t) lock; + } + END_TIMING; + } + + (void) sink; + return (Datum) 0; +} diff --git a/src/test/modules/microbench/lwlock/install.sql b/src/test/modules/microbench/lwlock/install.sql new file mode 100644 index 00000000000..9bf234837b1 --- /dev/null +++ b/src/test/modules/microbench/lwlock/install.sql @@ -0,0 +1,10 @@ +CREATE FUNCTION bench_lwlock( + IN n int8, + IN rounds int8 DEFAULT 1, + IN random bool DEFAULT true +) +RETURNS SETOF microbench_sample +AS 'MODULE_PATHNAME', 'bench_lwlock' +LANGUAGE C; + +REVOKE ALL ON FUNCTION bench_lwlock(int8, int8, bool) FROM PUBLIC; diff --git a/src/test/modules/microbench/lwlock/query.sql b/src/test/modules/microbench/lwlock/query.sql new file mode 100644 index 00000000000..16c1fd1dfe4 --- /dev/null +++ b/src/test/modules/microbench/lwlock/query.sql @@ -0,0 +1,8 @@ +-- lwlock micro-benchmark query + +\pset format aligned + +SELECT * FROM format_microbench( + (SELECT array_agg(s ORDER BY s.id) + FROM bench_lwlock(:'n'::int8, :'rounds'::int8, true) AS s) +); diff --git a/src/test/modules/microbench/meson.build b/src/test/modules/microbench/meson.build new file mode 100644 index 00000000000..9836640a3df --- /dev/null +++ b/src/test/modules/microbench/meson.build @@ -0,0 +1,33 @@ +# Copyright (c) 2024-2026, PostgreSQL Global Development Group + +microbench_tests = [ + 'lwlock', +] + +microbench_sources = files( + '@0@/bench.c'.format(test) for test in microbench_tests +) + +if host_system == 'windows' + microbench_sources += rc_lib_gen.process(win32ver_rc, extra_args: [ + '--NAME', 'microbench', + '--FILEDESC', 'microbench - micro-benchmark suite',]) +endif + +microbench_sql = custom_target('microbench--1.0.sql', + output: 'microbench--1.0.sql', + input: files('microbench--1.0.sql.head') + files( + '@0@/install.sql'.format(test) for test in microbench_tests + ), + command: [find_program('cat'), '@INPUT@'], + build_by_default: true, +) + +microbench = shared_module('microbench', + microbench_sources, + kwargs: pg_test_mod_args, +) +test_install_libs += microbench + +test_install_data += microbench_sql +test_install_data += files('microbench.control') diff --git a/src/test/modules/microbench/microbench-head--1.0.sql b/src/test/modules/microbench/microbench-head--1.0.sql new file mode 100644 index 00000000000..48c5143843a --- /dev/null +++ b/src/test/modules/microbench/microbench-head--1.0.sql @@ -0,0 +1,44 @@ +/* src/test/modules/microbench/microbench--1.0.sql */ +/* Generated from microbench--1.0.sql.head and per-test install.sql files. */ + +-- complain if script is sourced in psql, rather than via CREATE EXTENSION +\echo Use "CREATE EXTENSION microbench" to load this file. \quit + +CREATE DOMAIN microbench_format AS numeric(15, 2); + +CREATE TYPE microbench_sample AS ( + op text, + avg_ns float8, + batch_size int8, + id int8 +); + +CREATE TYPE microbench_stats AS ( + op text, + avg microbench_format, + min microbench_format, + q1 microbench_format, + med microbench_format, + q3 microbench_format, + max microbench_format, + std microbench_format +); + +CREATE FUNCTION format_microbench(samples microbench_sample[]) +RETURNS SETOF microbench_stats +LANGUAGE sql +STABLE +AS $$ + SELECT + s.op, + avg(s.avg_ns), + min(s.avg_ns), + percentile_cont(0.25) WITHIN GROUP (ORDER BY s.avg_ns), + percentile_cont(0.50) WITHIN GROUP (ORDER BY s.avg_ns), + percentile_cont(0.75) WITHIN GROUP (ORDER BY s.avg_ns), + max(s.avg_ns), + stddev(s.avg_ns) + FROM unnest(samples) AS s + GROUP BY s.op + ORDER BY min(s.id); +$$; diff --git a/src/test/modules/microbench/microbench.control b/src/test/modules/microbench/microbench.control new file mode 100644 index 00000000000..16aaf002517 --- /dev/null +++ b/src/test/modules/microbench/microbench.control @@ -0,0 +1,4 @@ +comment = 'micro-benchmarks for LWLock acquire/release paths' +default_version = '1.0' +module_pathname = '$libdir/microbench' +relocatable = true diff --git a/src/test/modules/microbench/randomize.h b/src/test/modules/microbench/randomize.h new file mode 100644 index 00000000000..e6eb3e32542 --- /dev/null +++ b/src/test/modules/microbench/randomize.h @@ -0,0 +1,23 @@ +#ifndef MICROBENCH_RANDOMIZE_H +#define MICROBENCH_RANDOMIZE_H + +#include "common/pg_prng.h" + +/* + * Fisher-Yates shuffle of a pointer array. + * https://en.wikipedia.org/wiki/Fisher-Yates_shuffle + */ +static inline void +shuffle_pointers(pg_prng_state *rng, void **ptrs, int count) +{ + for (int i = count - 1; i > 0; i--) + { + int k = (int) pg_prng_int64_range(rng, 0, i); + void *tmp = ptrs[i]; + + ptrs[i] = ptrs[k]; + ptrs[k] = tmp; + } +} + +#endif diff --git a/src/test/modules/microbench/scripts/run-test.sh b/src/test/modules/microbench/scripts/run-test.sh new file mode 100755 index 00000000000..ee9e29d7b49 --- /dev/null +++ b/src/test/modules/microbench/scripts/run-test.sh @@ -0,0 +1,135 @@ +#!/usr/bin/env bash +# +# Run one microbench test folder. +# +# Usage: run-test.sh TEST +# Env: TOP_BUILDDIR, PG_CONFIG, MICROBENCH_PORT (default 55432), +# MICROBENCH_N (default 128), MICROBENCH_ROUNDS (default 1000) +# +set -euo pipefail + +TEST=${1:?usage: run-test.sh TEST} + +SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +MODULE_DIR=$(cd "$SCRIPT_DIR/.." && pwd) +TOP_BUILDDIR=${TOP_BUILDDIR:-$(cd "$MODULE_DIR/../../../.." && pwd)} +PORT=${MICROBENCH_PORT:-55432} +LOGDIR="$MODULE_DIR/.tmp_check/log" +DATADIR="$MODULE_DIR/.tmp_check/data" +N=${MICROBENCH_N:-128} +ROUNDS=${MICROBENCH_ROUNDS:-1000} + +log() { printf '%s\n' "$*" >&2; } + +test -f "$MODULE_DIR/$TEST/query.sql" || { + log "missing $MODULE_DIR/$TEST/query.sql" + exit 1 +} +pick_pg_config() { + if [[ -n "${PG_CONFIG:-}" && -x "$PG_CONFIG" ]]; then + printf '%s\n' "$PG_CONFIG" + return + fi + + local makefile_global="$TOP_BUILDDIR/src/Makefile.global" + if [[ -f "$makefile_global" ]]; then + local prefix candidate + + prefix=$(sed -n 's/^prefix := //p' "$makefile_global" | head -1) + if [[ -n "$prefix" ]]; then + candidate="$prefix/bin/pg_config" + if [[ -x "$candidate" ]]; then + printf '%s\n' "$candidate" + return + fi + log "configured prefix $prefix has no executable pg_config at $candidate" + fi + fi + + return 1 +} + +PG_CONFIG=$(pick_pg_config) || { + log "no PostgreSQL install found; set PG_CONFIG or run configure && make install at repo root" + exit 1 +} + +BINDIR=$("$PG_CONFIG" --bindir) +LIBDIR=$("$PG_CONFIG" --libdir) +log "==> using $($PG_CONFIG --version) [$BINDIR]" + +log "==> building and installing microbench..." +make -C "$MODULE_DIR" MICROBENCH_POSTGRES="$BINDIR/postgres" install + +export PATH="$BINDIR:$PATH" +case "$(uname -s)" in + Darwin) export DYLD_LIBRARY_PATH="$LIBDIR:${DYLD_LIBRARY_PATH:-}" ;; + *) export LD_LIBRARY_PATH="$LIBDIR:${LD_LIBRARY_PATH:-}" ;; +esac + +mkdir -p "$LOGDIR" + +postgres_build_id() { + # Re-init when the installed postgres binary changes (catalog bumps, rebuilds). + printf '%s:%s' "$("$BINDIR/postgres" --version)" \ + "$(shasum -a 256 "$BINDIR/postgres" | awk '{print $1}')" +} + +ensure_datadir() { + local build_id stamp_file="$DATADIR/.microbench_build_id" + + build_id=$(postgres_build_id) + if [[ -f "$DATADIR/PG_VERSION" && -f "$stamp_file" && "$(cat "$stamp_file")" == "$build_id" ]]; then + return 0 + fi + + if [[ -f "$DATADIR/PG_VERSION" ]]; then + log "==> stale datadir (postgres rebuilt); re-initdb..." + else + log "==> initdb..." + fi + + rm -rf "$DATADIR" + "$BINDIR/initdb" -D "$DATADIR" --auth trust --no-sync --no-instructions -N \ + >"$LOGDIR/initdb.log" 2>&1 + printf '%s\n' "$build_id" > "$stamp_file" +} + +ensure_datadir + +cleanup() { + if "$BINDIR/pg_ctl" -D "$DATADIR" status >/dev/null 2>&1; then + "$BINDIR/pg_ctl" -D "$DATADIR" stop -m fast >>"$LOGDIR/pg_ctl.log" 2>&1 || true + fi +} +trap cleanup EXIT + +if ! "$BINDIR/pg_ctl" -D "$DATADIR" status >/dev/null 2>&1; then + log "==> starting postgres on port $PORT..." + if ! "$BINDIR/pg_ctl" -D "$DATADIR" -l "$LOGDIR/postgres.log" \ + -o "-p $PORT -F -h '' -c shared_buffers=128MB" start \ + >>"$LOGDIR/pg_ctl.log" 2>&1; then + if grep -q 'incompatible with server' "$LOGDIR/postgres.log"; then + log "==> postgres rejected datadir; re-initdb..." + rm -rf "$DATADIR" + ensure_datadir + "$BINDIR/pg_ctl" -D "$DATADIR" -l "$LOGDIR/postgres.log" \ + -o "-p $PORT -F -h '' -c shared_buffers=128MB" start \ + >>"$LOGDIR/pg_ctl.log" 2>&1 + else + log "pg_ctl start failed; see $LOGDIR/postgres.log and $LOGDIR/pg_ctl.log" + exit 1 + fi + fi +fi + +log "==> CREATE EXTENSION microbench" +: >"$LOGDIR/psql.log" +"$BINDIR/psql" -v ON_ERROR_STOP=1 -p "$PORT" -d postgres \ + -c "DROP EXTENSION IF EXISTS microbench CASCADE; CREATE EXTENSION microbench;" \ + >>"$LOGDIR/psql.log" 2>&1 + +log "==> running $TEST/query.sql (n=$N rounds=$ROUNDS)" +"$BINDIR/psql" -v ON_ERROR_STOP=1 -p "$PORT" -d postgres \ + -v n="$N" -v rounds="$ROUNDS" \ + -f "$MODULE_DIR/$TEST/query.sql" diff --git a/src/test/modules/microbench/timing-magic.h b/src/test/modules/microbench/timing-magic.h new file mode 100644 index 00000000000..54318841f64 --- /dev/null +++ b/src/test/modules/microbench/timing-magic.h @@ -0,0 +1,30 @@ +#ifndef MICROBENCH_TIMING_MAGIC_H +#define MICROBENCH_TIMING_MAGIC_H + +#include "portability/instr_time.h" + +#define INIT_TIMING_SCOPE() \ + int64 timing_operation_id = 0 + +#define BEGIN_TIMING(name, n) \ + do { \ + instr_time t0, t1, dt; \ + Datum values[4]; \ + bool nulls[4] = {0}; \ + values[0] = CStringGetTextDatum(name); \ + INSTR_TIME_SET_CURRENT_FAST(t0); \ + for (int64 i = 0; i < (n); ++i) \ + { + +#define END_TIMING \ + } \ + INSTR_TIME_SET_CURRENT_FAST(t1); \ + INSTR_TIME_SET_ZERO(dt); \ + INSTR_TIME_ACCUM_DIFF(dt, t1, t0); \ + values[1] = Float8GetDatum((double) INSTR_TIME_GET_NANOSEC(dt) / (double) (n)); \ + values[2] = Int64GetDatum(n); \ + values[3] = Int64GetDatum(++timing_operation_id); \ + tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls); \ + } while (0) + +#endif -- 2.53.0
0003-lwlock-Save-only-pointer.patch (application/octet-stream, 6.5K) download From b25f6db5693d0ca7d37b394145796b3bf96a35c1 Mon Sep 17 00:00:00 2001 From: Alexandre Felipe <o.alexandre.felipe@gmail.com> Date: Tue, 18 Aug 2026 01:06:17 +0100 Subject: [PATCH 3/5] lwlock: Save only pointer Instead of saving the mode of the lock infer it from the lock itself op | avg | min | q1 | med | q3 | max | std -------------+-------+------+-------+-------+-------+--------+------ spin-lock | 14.41 | 7.81 | 12.04 | 15.95 | 16.28 | 82.69 | 4.15 LWLock-ex | 6.97 | 6.18 | 6.84 | 6.84 | 6.84 | 47.53 | 1.71 LWLock-sh | 7.15 | 6.51 | 6.84 | 6.84 | 6.84 | 248.70 | 7.68 lw-ex-mode | 7.93 | 6.84 | 7.48 | 7.48 | 7.81 | 308.59 | 9.67 lw-ex-last | 6.75 | 6.18 | 6.51 | 6.52 | 6.84 | 26.04 | 0.82 lw-sh-mode | 7.57 | 6.84 | 7.48 | 7.48 | 7.81 | 16.28 | 0.61 lw-sh-last | 6.79 | 6.18 | 6.51 | 6.52 | 6.84 | 113.61 | 3.42 LWLock-cond | 6.16 | 5.21 | 5.86 | 5.86 | 6.19 | 63.80 | 1.95 nop | 0.72 | 0.32 | 0.65 | 0.66 | 0.98 | 2.93 | 0.27 --- src/backend/storage/lmgr/lwlock.c | 52 ++++++++++++++----------------- 1 file changed, 23 insertions(+), 29 deletions(-) diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c index f572b4a4f84..444b5ed37ec 100644 --- a/src/backend/storage/lmgr/lwlock.c +++ b/src/backend/storage/lmgr/lwlock.c @@ -156,15 +156,9 @@ LWLockPadded *MainLWLockArray = NULL; */ #define MAX_SIMUL_LWLOCKS 200 -/* struct representing the LWLocks we're holding */ -typedef struct LWLockHandle -{ - LWLock *lock; - LWLockMode mode; -} LWLockHandle; static int num_held_lwlocks = 0; -static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]; +static LWLock *held_lwlocks[MAX_SIMUL_LWLOCKS]; /* Maximum number of LWLock tranches that can be assigned by extensions */ #define MAX_USER_DEFINED_TRANCHES 256 @@ -229,6 +223,12 @@ static const char *GetLWTrancheName(uint16 trancheId); #define T_NAME(lock) \ GetLWTrancheName((lock)->tranche) +static LWLockMode +LWLockInferLockMode(LWLock *lock) +{ + return (pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE) ? + LW_EXCLUSIVE : LW_SHARED; +} #ifdef LWLOCK_STATS typedef struct lwlock_stats_key { @@ -1298,8 +1298,7 @@ LWLockAcquireCommon(LWLock *lock, LWLockMode mode) TRACE_POSTGRESQL_LWLOCK_ACQUIRE(T_NAME(lock), mode); /* Add lock to list of locks held by this backend */ - held_lwlocks[num_held_lwlocks].lock = lock; - held_lwlocks[num_held_lwlocks++].mode = mode; + held_lwlocks[num_held_lwlocks++] = lock; /* * Fix the process wait semaphore's count for any absorbed wakeups. @@ -1376,8 +1375,7 @@ LWLockConditionalAcquire(LWLock *lock, LWLockMode mode) else { /* Add lock to list of locks held by this backend */ - held_lwlocks[num_held_lwlocks].lock = lock; - held_lwlocks[num_held_lwlocks++].mode = mode; + held_lwlocks[num_held_lwlocks++] = lock; if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_ENABLED()) TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(T_NAME(lock), mode); } @@ -1507,8 +1505,7 @@ LWLockAcquireOrWait(LWLock *lock, LWLockMode mode) { LOG_LWDEBUG("LWLockAcquireOrWait", lock, "succeeded"); /* Add lock to list of locks held by this backend */ - held_lwlocks[num_held_lwlocks].lock = lock; - held_lwlocks[num_held_lwlocks++].mode = mode; + held_lwlocks[num_held_lwlocks++] = lock; if (TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_ENABLED()) TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT(T_NAME(lock), mode); } @@ -1850,13 +1847,12 @@ extern void LWLockRelease(LWLock *lock) { int i = num_held_lwlocks - 1; - LWLockMode mode; + LWLockMode mode = LWLockInferLockMode(lock); /* * Fast path: check if this is the most recently acquired lock. */ - if (likely(i >= 0 && held_lwlocks[i].lock == lock)) + if (likely(i >= 0 && held_lwlocks[i] == lock)) { - mode = held_lwlocks[i].mode; num_held_lwlocks = i; LWLockReleaseInternal(lock, mode); return; @@ -1867,14 +1863,12 @@ LWLockRelease(LWLock *lock) */ for (i = num_held_lwlocks; --i >= 0;) - if (lock == held_lwlocks[i].lock) + if (lock == held_lwlocks[i]) break; if (i < 0) elog(ERROR, "lock %s is not held", T_NAME(lock)); - mode = held_lwlocks[i].mode; - num_held_lwlocks--; for (; i < num_held_lwlocks; i++) held_lwlocks[i] = held_lwlocks[i + 1]; @@ -1896,9 +1890,9 @@ LWLockReleaseCommon(LWLock *lock, LWLockMode mode) { int i = num_held_lwlocks - 1; - if (likely(i >= 0 && held_lwlocks[i].lock == lock)) + if (likely(i >= 0 && held_lwlocks[i] == lock)) { - Assert(held_lwlocks[i].mode == mode); + Assert(LWLockInferLockMode(lock) == mode); num_held_lwlocks = i; LWLockReleaseInternal(lock, mode); return; @@ -1906,13 +1900,13 @@ LWLockReleaseCommon(LWLock *lock, LWLockMode mode) for (;i >= 0; --i) - if (lock == held_lwlocks[i].lock) + if (lock == held_lwlocks[i]) break; if (i < 0) elog(ERROR, "lock %s is not held", T_NAME(lock)); - Assert(held_lwlocks[i].mode == mode); + Assert(LWLockInferLockMode(lock) == mode); num_held_lwlocks--; for (; i < num_held_lwlocks; i++) @@ -1955,8 +1949,8 @@ static pg_always_inline void LWLockReleaseLastCommon(LWLock *lock, LWLockMode mode) { Assert(num_held_lwlocks > 0); - Assert(held_lwlocks[num_held_lwlocks - 1].lock == lock); - Assert(held_lwlocks[num_held_lwlocks - 1].mode == mode); + Assert(held_lwlocks[num_held_lwlocks - 1] == lock); + Assert(LWLockInferLockMode(lock) == mode); num_held_lwlocks--; LWLockReleaseInternal(lock, mode); @@ -2022,7 +2016,7 @@ LWLockReleaseAll(void) { HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */ - LWLockRelease(held_lwlocks[num_held_lwlocks - 1].lock); + LWLockRelease(held_lwlocks[num_held_lwlocks - 1]); } Assert(num_held_lwlocks == 0); @@ -2041,7 +2035,7 @@ LWLockHeldByMe(LWLock *lock) for (i = 0; i < num_held_lwlocks; i++) { - if (held_lwlocks[i].lock == lock) + if (held_lwlocks[i] == lock) return true; } return false; @@ -2064,7 +2058,7 @@ LWLockAnyHeldByMe(LWLock *lock, int nlocks, size_t stride) end = begin + nlocks * stride; for (i = 0; i < num_held_lwlocks; i++) { - held_lock_addr = (char *) held_lwlocks[i].lock; + held_lock_addr = (char *) held_lwlocks[i]; if (held_lock_addr >= begin && held_lock_addr < end && (held_lock_addr - begin) % stride == 0) @@ -2085,7 +2079,7 @@ LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode) for (i = 0; i < num_held_lwlocks; i++) { - if (held_lwlocks[i].lock == lock && held_lwlocks[i].mode == mode) + if (held_lwlocks[i] == lock && LWLockInferLockMode(lock) == mode) return true; } return false; -- 2.53.0
0005-Inline-attempt-and-fold-acquire-loop.patch (application/octet-stream, 4.5K) download From 66e2fec92776fc7a55d61e4916a156b60d73b8dc Mon Sep 17 00:00:00 2001 From: Alexandre Felipe <o.alexandre.felipe@gmail.com> Date: Mon, 24 Aug 2026 21:44:30 +0100 Subject: [PATCH 5/5] Inline attempt and fold acquire loop By inlining LWLockAttemptLock we may reduce the amount of fetched code. The previous code was always breaking the loop running a small common code at the bottom of the function likely on a different cache line (if not two). Might improve prefetching, or even terminate the function before fetching one more cache line. Using queued and !queued we can reuse the inline LWLock call at the cost of one one queued = false; and an if(!queued) in the uncontended path. op | avg | min | q1 | med | q3 | max | std -------------+-------+------+-------+-------+-------+-------+------ spin-lock | 14.26 | 7.81 | 12.37 | 15.63 | 16.28 | 21.16 | 3.13 LWLock-ex | 6.21 | 5.53 | 6.18 | 6.19 | 6.19 | 14.98 | 0.37 LWLock-sh | 6.22 | 5.53 | 6.18 | 6.19 | 6.19 | 8.46 | 0.25 LWLock-X | 9.02 | 7.81 | 8.79 | 9.12 | 9.44 | 12.37 | 0.49 lw-ex-mode | 8.99 | 7.81 | 8.79 | 9.11 | 9.12 | 13.02 | 0.49 lw-ex-last | 5.80 | 5.53 | 5.54 | 5.86 | 5.86 | 8.46 | 0.28 lw-sh-mode | 9.02 | 7.81 | 8.79 | 9.11 | 9.12 | 13.67 | 0.52 lw-sh-last | 5.85 | 5.21 | 5.54 | 5.86 | 5.86 | 49.48 | 1.41 LWLock-cond | 6.07 | 5.20 | 5.86 | 5.86 | 6.19 | 18.88 | 0.71 nop | 0.86 | 0.32 | 0.66 | 0.98 | 0.98 | 1.63 | 0.17 --- src/backend/storage/lmgr/lwlock.c | 61 ++++++++++++++++--------------- 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c index 00b589f158e..ab7ec3bd767 100644 --- a/src/backend/storage/lmgr/lwlock.c +++ b/src/backend/storage/lmgr/lwlock.c @@ -760,7 +760,7 @@ GetLWLockIdentifier(uint32 classId, uint16 eventId) * * Returns true if the lock isn't free and we need to wait. */ -static bool +static pg_always_inline bool LWLockAttemptLock(LWLock *lock, LWLockMode mode) { uint32 old_state; @@ -1152,6 +1152,7 @@ LWLockAcquireCommon(LWLock *lock, LWLockMode mode) PGPROC *proc = MyProc; bool result = true; int extraWaits = 0; + bool queued; #ifdef LWLOCK_STATS lwlock_stats *lwstats; @@ -1216,8 +1217,30 @@ LWLockAcquireCommon(LWLock *lock, LWLockMode mode) if (!mustwait) { - LOG_LWDEBUG("LWLockAcquire", lock, "immediately acquired lock"); - break; /* got the lock */ + if (TRACE_POSTGRESQL_LWLOCK_ACQUIRE_ENABLED()) + TRACE_POSTGRESQL_LWLOCK_ACQUIRE(T_NAME(lock), mode); + + /* Add lock to list of locks held by this backend */ + held_lwlocks[num_held_lwlocks++] = lock; + + /* + * Fix the process wait semaphore's count for any absorbed wakeups. + */ + while (extraWaits-- > 0) + PGSemaphoreUnlock(proc->sem); + + if(!queued) + { + LOG_LWDEBUG("LWLockAcquire", lock, "immediately acquired lock"); + return result; + } + else + { + LOG_LWDEBUG("LWLockAcquire", lock, "acquired, undoing queue"); + + LWLockDequeueSelf(lock); + return result; + } } /* @@ -1230,20 +1253,11 @@ LWLockAcquireCommon(LWLock *lock, LWLockMode mode) * other locker will see our queue entries when releasing since they * existed before we checked for the lock. */ - - /* add to the queue */ - LWLockQueueSelf(lock, mode); - - /* we're now guaranteed to be woken up if necessary */ - mustwait = LWLockAttemptLock(lock, mode); - - /* ok, grabbed the lock the second time round, need to undo queueing */ - if (!mustwait) + if(!queued) { - LOG_LWDEBUG("LWLockAcquire", lock, "acquired, undoing queue"); - - LWLockDequeueSelf(lock); - break; + /* add to the queue */ + LWLockQueueSelf(lock, mode); + continue; } /* @@ -1287,26 +1301,13 @@ LWLockAcquireCommon(LWLock *lock, LWLockMode mode) if (TRACE_POSTGRESQL_LWLOCK_WAIT_DONE_ENABLED()) TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode); LWLockReportWaitEnd(); - + queued = false; LOG_LWDEBUG("LWLockAcquire", lock, "awakened"); /* Now loop back and try to acquire lock again. */ result = false; } - if (TRACE_POSTGRESQL_LWLOCK_ACQUIRE_ENABLED()) - TRACE_POSTGRESQL_LWLOCK_ACQUIRE(T_NAME(lock), mode); - - /* Add lock to list of locks held by this backend */ - held_lwlocks[num_held_lwlocks++] = lock; - - /* - * Fix the process wait semaphore's count for any absorbed wakeups. - */ - while (extraWaits-- > 0) - PGSemaphoreUnlock(proc->sem); - - return result; } bool LWLockAcquireX(LWLock *lock, LWLockMode mode) { -- 2.53.0
^ permalink raw reply [nested|flat] 13+ messages in thread

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-25 10:37  Yuhang Qiu <iamqyh@gmail.com>
  parent: Alexandre Felipe <o.alexandre.felipe@gmail.com>
  1 sibling, 1 reply; 13+ messages in thread

From: Yuhang Qiu @ 2026-08-25 10:37 UTC (permalink / raw)
  To: Alexandre Felipe <o.alexandre.felipe@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Alexandre,

Thanks for sharing the experiments. I have a few concerns.

The benchmark runs in a single backend. This mainly measures instruction and
branch overhead. Saving a few nanoseconds here does not necessarily result
in a measurable end-to-end improvement.

The patch also adds more interfaces and makes the locking code harder to use
and maintain. Some changes seem to move costs rather than remove them.

In 0002, LWLockAcquire is declared as a non-static inline function, while its
external definition is removed, when the compiler does not inline it, for
example with -O0, this whill leave an unresolved LWLockAcquire symbol and
causes a link failure: 
```C
inline bool LWLockAcquire(LWLock *lock, LWLockMode mode)
```

In 0005, queued is not initialized and is never set to true after queueing,
This can cause repeated queueing, incorrect dequeueing, or prevent the backend
from reaching the normal sleep path:
```C
bool queued;

if (!queued)
{
LWLockQueueSelf(lock, mode);
continue;
}
```

I think it would be more useful to reduce unnecessary LWLock acquisitions or 
contention in higher-level code paths, such as buffer mapping and WAL buffers.
For LWLock itself, the important part are atomic operations and cache-line
contention (though there might be no lock contention, but at CPU level, emmm),
wait-list contention, sleep/wakeup mechanism, and fairness...

Best Regards,
Yuhang Qiu.







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

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-08-26 16:01  Andres Freund <andres@anarazel.de>
  parent: Alexandre Felipe <o.alexandre.felipe@gmail.com>
  1 sibling, 0 replies; 13+ messages in thread

From: Andres Freund @ 2026-08-26 16:01 UTC (permalink / raw)
  To: Alexandre Felipe <o.alexandre.felipe@gmail.com>; +Cc: Yuhang Qiu <iamqyh@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2026-08-24 22:01:43 +0100, Alexandre Felipe wrote:
> There are no algorithmic changes. The changes are about
> 
> 0002 having two distinct paths for LW_EXCLUSIVE and LW_SHARED,
> the rest is diminishing returns. And also added LWLockReleaseLast,
> added wrappers as inline functions in lwlock.h that compiles the
> current code base replacing the calls
> LWLockAcquire(lock, LW_EXCLUSIVE | LW_SHARED) by the
> LWLockAcquire(Exclusive|Shared)(lock)
> 
> 
> 
> 0003 reading the mode from the LWLock state and saving space and time
> storing it in the held lwlocks array.
> 0004 well, bring LWLock(Acquire/Release)X external functions that take
> mode as a parameter (a baseline).
> 0005 Inlined LWLockAttemptLock and folded the loop, placing a single
> LWLockAttemptLock at the top of the loop followed by the common logic
> (previously at the end bottom of the function), then enqueue and continue
> or wait.


> From 7e2fe005525d59c4def5ac0f1060d3d4bfa43351 Mon Sep 17 00:00:00 2001
> From: Alexandre Felipe <o.alexandre.felipe@gmail.com>
> Date: Mon, 17 Aug 2026 18:19:43 +0100
> Subject: [PATCH 1/5] Benchmark
> 
> This adds a module for benchmarking LWLocks in a tight loop.

I don't believe that's a particulary interesting test. You don't normally take
a lock to then not do anything when covered by the lock.



> From 139f5d67266c94f96f3e88b056c297307efacb32 Mon Sep 17 00:00:00 2001
> From: Alexandre Felipe <o.alexandre.felipe@gmail.com>
> Date: Mon, 17 Aug 2026 18:41:39 +0100
> Subject: [PATCH 2/5] LWLock fast paths
> 
> inline LWLockAcquire(LWLock* , LWLockMode)
> +- extern LWLockAcquireShared(LWLock*)
> |  +- fast LWLockAcquireCommon(LWLock*, LW_SHARED)
> |     +- fast LWLockAttemptLock(LWLock*, LW_SHARED)
> |     +- ... slow path
> +- extern LWLockACquireExclusive(LWLock*)
>    +- fast LWLockAcquireCommon(LWLock*, LW_EXCLUSIVE)
>       +- fast LWLockAttemptLock(LWLock*, LW_EXCLUSIVE)
>       +- ... slow path
> 
> LWLock tracking only stores (LWLock*), the mode can be inferred at
> any time from the LWLock state. since at any time either the number
> of exclusive locks or the number of shared locks on a LWLock must
> be zero. If a lock is currently held, one of them will be non-zero.

> Is reading the mode from the lock state in the hot path a concern?

Yes, that sounds like a bad idea. The lock state on a somewhat contended lock
tends to bounce very heavily between cores / nodes. Pulling it into shared
state before the atomic operation is a bad idea.

I think that's a clear no-go.


> This patch provides a LWLockRelease(LWLock, LWLockMode) that uses
> an architecture similar to LWLockAcquire.
> 
> inline LWLockReleaseMode(LWLock* , LWLockMode)
> +- extern LWLockReleaseShared(LWLock*)
> |  +- if(lock is at the top of held_lwlocks)
> |  |  fast LWLockReleaseCommon(LWLock*, LW_SHARED)
> |  +- ... slow path
> +- extern LWLockReleaseExclusive(LWLock*)
>    +- if(lock is at the top of held_lwlocks)
>    |  fast LWLockReleaseCommon(LWLock*, LW_EXCLUSIVE)
>    +- ... slow path
> 
> Is the top of the stack check in the hot path a concern?
> This patch provides a LWLockReleaseLast(LWLock*, LWLockMode),
> that only checks for the existence of a lock.

I doubt the gain of eliding am-i-on-the-top-of-the-stack check is worth it.
To prove that it is you would really need to show in a more realistic scenario
that the gain is worth the interface complexity.


Greetings,

Andres Freund






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

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-09-09 09:41  Alexandre Felipe <o.alexandre.felipe@gmail.com>
  parent: Yuhang Qiu <iamqyh@gmail.com>
  0 siblings, 1 reply; 13+ messages in thread

From: Alexandre Felipe @ 2026-09-09 09:41 UTC (permalink / raw)
  To: Yuhang Qiu <iamqyh@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Aug 25, 2026 at 11:37 AM Yuhang Qiu <iamqyh@gmail.com> wrote:

> I think it would be more useful to reduce unnecessary LWLock acquisitions
> or
> contention in higher-level code paths, such as buffer mapping and WAL
> buffers.
> For LWLock itself, the important part are atomic operations and cache-line
> contention (though there might be no lock contention, but at CPU level,
> emmm),
> wait-list contention, sleep/wakeup mechanism, and fairness...
>

Experiments show that a LWLockAcquire(...) = 1 is 1000x - 10000x slower
than an
LWLockAcquire(...) = 0. So, what I want to propose here is a more granular
lock.

I see that the locks are already used in partitions, I know that in
BufTable we are
using 128 locks, but it could have millions, we don't do it because of the
overhead, possibly managing waiting lists, and so on.

This patch supports granular LW_EXCLUSIVE locks, the immediate application I
could see is in BufTable, where a lock partition could be further
subdivided in up
to 26 rooms. Shared locks contend to any exclusive lock as today, but
exclusive
locks to different runs can be held simultaneously. (decided to include a
patch
with this before sending).

When the last LW_SHARED is released, all non-overlapping waiters are
awakened
simultaneously, with no need to wait. A LW_EXCLUSIVE might not be put to
sleep
if they don't require the same rooms.

A fairness consideration here is that this implementation doesn't wake up
the
waiters in order. The contending shared locks always lose to uncontended
exclusive locks, this might lead to (1 exclusive) shared (2-exclusive 1
exclusive)*
blocking shared forever. But I hope it serves to illustrate the idea.

If this seems acceptable, the next steps could be (not necessarily in that
order)
(1) adding a PRIORITY bit to mode to control whether it goes before or
after;
(2) don't skip a LW_SHARED if it is first on queue;
(3) accepting rooms on LW_SHARED mode, and promoting uncontended
locks to LW_EXCLUSIVE on the required rooms when the number of waiters is
small.
(4) combining the approaches choosing to release the configuration that
results
in the highest number of waiters being awakened.

I suspect that there are some "Wait for X" cases that I am not handling.

Attachments: download all (2 files, .tar.gz)

0001-lwlock-LW_EXCLUSIVE-Rooms.patch (application/octet-stream, 16.7K) download From 38fea11563137df6d6bcfcce1e4cd14fee9cc818 Mon Sep 17 00:00:00 2001 From: Alexandre Felipe <o.alexandre.felipe@gmail.com> Date: Sun, 6 Sep 2026 01:20:31 +0100 Subject: [PATCH] lwlock: LW_EXCLUSIVE Rooms make clean; this patch changes LWLockMode enum. Currently LW_LOCK supports LW_SHARED and LW_EXCLUSIVE mode, LW_SHARED has no practical limits as it simply count holders and the counter range is [0, MAX_BACKENDS]. For LW_EXCLUSIVE mode it accepts exactly one holder at a time. This patch includes the concept of rooms, is the analogy of a hotel where EXCLUSIVE access is granted to each room individually. The implementation consists in tracking looks to 16 rooms. The backward compatible behaviour is locking all the rooms, when acquiring the LWLock in exclusive mode. Shared mode doesn't support rooms (as the same bits will be used to tracke count holders), and the behaviour is as if every shared lock acquires a LW_SHARED lock for every room. This doesn't change exclusive-shared contention, but can be employed to reduce exclusive-exclusive contention. --- src/backend/storage/lmgr/lwlock.c | 164 +++++++++++++++++++++--------- src/include/storage/lwlock.h | 93 +++++++++++++++-- src/include/storage/proc.h | 1 + 3 files changed, 202 insertions(+), 56 deletions(-) diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c index 82a1d4d2e26..2b54f6e49c4 100644 --- a/src/backend/storage/lmgr/lwlock.c +++ b/src/backend/storage/lmgr/lwlock.c @@ -46,7 +46,7 @@ * * For lock acquisition we use an atomic compare-and-exchange on the lockcount * variable. For exclusive lock we swap in a sentinel value - * (LW_VAL_EXCLUSIVE), for shared locks we count the number of holders. + * (LW_EXCLUSIVE), for shared locks we count the number of holders. * * To release the lock we use an atomic decrement to release the lock. If the * new value is zero (we get that atomically), we know we can/have to release @@ -100,13 +100,9 @@ #define LW_FLAG_MASK (((1<<LW_FLAG_BITS)-1)<<(32-LW_FLAG_BITS)) /* assumes MAX_BACKENDS is a (power of 2) - 1, checked below */ -#define LW_VAL_EXCLUSIVE (MAX_BACKENDS + 1) -#define LW_VAL_SHARED 1 - /* already (power of 2)-1, i.e. suitable for a mask */ -#define LW_SHARED_MASK MAX_BACKENDS -#define LW_LOCK_MASK (MAX_BACKENDS | LW_VAL_EXCLUSIVE) - +#define LW_SHARED_MASK (MAX_BACKENDS << 1) +#define LW_LOCK_MASK (LW_SHARED_MASK | LW_EXCLUSIVE) StaticAssertDecl(((MAX_BACKENDS + 1) & MAX_BACKENDS) == 0, "MAX_BACKENDS + 1 needs to be a power of 2"); @@ -114,8 +110,11 @@ StaticAssertDecl(((MAX_BACKENDS + 1) & MAX_BACKENDS) == 0, StaticAssertDecl((MAX_BACKENDS & LW_FLAG_MASK) == 0, "MAX_BACKENDS and LW_FLAG_MASK overlap"); -StaticAssertDecl((LW_VAL_EXCLUSIVE & LW_FLAG_MASK) == 0, - "LW_VAL_EXCLUSIVE and LW_FLAG_MASK overlap"); +StaticAssertDecl((LW_EXCLUSIVE & LW_FLAG_MASK) == 0, + "LW_EXCLUSIVE and LW_FLAG_MASK overlap"); + +StaticAssertDecl((LW_LOCK_ROOM_MASK & LW_FLAG_MASK) == 0, + "LW_LOCK_ROOM_MASK and LW_FLAG_MASK overlap"); /* * There are three sorts of LWLock "tranches": @@ -267,7 +266,7 @@ PRINT_LWDEBUG(const char *where, LWLock *lock, LWLockMode mode) errmsg_internal("%d: %s(%s %p): excl %u shared %u haswaiters %u waiters %u waking %d", MyProcPid, where, T_NAME(lock), lock, - (state & LW_VAL_EXCLUSIVE) != 0, + (state & LW_EXCLUSIVE) != 0, state & LW_SHARED_MASK, (state & LW_FLAG_HAS_WAITERS) != 0, pg_atomic_read_u32(&lock->nwaiters), @@ -765,7 +764,7 @@ LWLockAttemptLock(LWLock *lock, LWLockMode mode) { uint32 old_state; - Assert(mode == LW_EXCLUSIVE || mode == LW_SHARED); + Assert(mode == LW_SHARED || (mode & LW_LOCK_MODE_MASK) == LW_EXCLUSIVE); /* * Read once outside the loop, later iterations will get the newer value @@ -781,17 +780,24 @@ LWLockAttemptLock(LWLock *lock, LWLockMode mode) desired_state = old_state; - if (mode == LW_EXCLUSIVE) + if ((mode & LW_LOCK_MODE_MASK) == LW_EXCLUSIVE) { - lock_free = (old_state & LW_LOCK_MASK) == 0; + uint32 rooms = mode & LW_LOCK_ROOM_MASK; + Assert(rooms != 0); + + if (old_state & LW_EXCLUSIVE) + lock_free = (old_state & rooms) == 0; /* rooms vs rooms */ + else + lock_free = (old_state & LW_SHARED_MASK) == 0; /* any shared count blocks */ + if (lock_free) - desired_state += LW_VAL_EXCLUSIVE; + desired_state |= LW_EXCLUSIVE | rooms; } else { - lock_free = (old_state & LW_VAL_EXCLUSIVE) == 0; + lock_free = (old_state & LW_EXCLUSIVE) == 0; if (lock_free) - desired_state += LW_VAL_SHARED; + desired_state += LW_SHARED; } /* @@ -811,7 +817,7 @@ LWLockAttemptLock(LWLock *lock, LWLockMode mode) { /* Great! Got the lock. */ #ifdef LOCK_DEBUG - if (mode == LW_EXCLUSIVE) + if ((mode & LW_LOCK_MODE_MASK) == LW_EXCLUSIVE) lock->owner = MyProc; #endif return false; @@ -903,8 +909,10 @@ LWLockWaitListUnlock(LWLock *lock) static void LWLockWakeup(LWLock *lock) { + /* will be set to LW_EXCLUSIVE or LW_SHARED later */ + LWLockMode awaking_mode = LW_WAIT_UNTIL_FREE; bool new_wake_in_progress = false; - bool wokeup_somebody = false; + uint32 held_rooms = 0; proclist_head wakeup; proclist_mutable_iter iter; @@ -913,11 +921,25 @@ LWLockWakeup(LWLock *lock) /* lock wait list while collecting backends to wake up */ LWLockWaitListLock(lock); + { + uint32 state = pg_atomic_read_u32(&lock->state); + + if (state & LW_EXCLUSIVE) + held_rooms = state & LW_LOCK_ROOM_MASK; + } + proclist_foreach_modify(iter, &lock->waiters, lwWaitLink) { PGPROC *waiter = GetPGProcByNumber(iter.cur); - if (wokeup_somebody && waiter->lwWaitMode == LW_EXCLUSIVE) + /* + * Don't mix LW_SHARED and LW_EXCLUSIVE + */ + if (new_wake_in_progress && waiter->lwWaitMode != awaking_mode) + continue; + + if (waiter->lwWaitMode == LW_EXCLUSIVE && + (waiter->lwLockRoom & held_rooms) != 0) continue; proclist_delete(&lock->waiters, iter.cur, lwWaitLink); @@ -931,11 +953,7 @@ LWLockWakeup(LWLock *lock) * automatically. */ new_wake_in_progress = true; - - /* - * Don't wakeup (further) exclusive locks. - */ - wokeup_somebody = true; + awaking_mode = waiter->lwWaitMode; } /* @@ -947,12 +965,17 @@ LWLockWakeup(LWLock *lock) Assert(waiter->lwWaiting == LW_WS_WAITING); waiter->lwWaiting = LW_WS_PENDING_WAKEUP; - /* - * Once we've woken up an exclusive lock, there's no point in waking - * up anybody else. - */ if (waiter->lwWaitMode == LW_EXCLUSIVE) - break; + { + held_rooms |= waiter->lwLockRoom; + + /* + * Once we've woken up an exclusive lock that covers all remaining + * rooms, there's no point in waking up anybody else. + */ + if (held_rooms == LW_LOCK_ROOM_MASK) + break; + } } Assert(proclist_is_empty(&wakeup) || pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS); @@ -1025,7 +1048,20 @@ LWLockQueueSelf(LWLock *lock, LWLockMode mode) if (MyProc == NULL) elog(PANIC, "cannot wait without a PGPROC structure"); - if (MyProc->lwWaiting != LW_WS_NOT_WAITING) + if (MyProc->lwWaiting == LW_WS_PENDING_WAKEUP) + { + /* + * Woken but not yet signalled; wait like LWLockDequeueSelf() so we + * never re-queue while still in a wakeup handoff. + */ + for (;;) + { + PGSemaphoreLock(MyProc->sem); + if (MyProc->lwWaiting == LW_WS_NOT_WAITING) + break; + } + } + else if (MyProc->lwWaiting != LW_WS_NOT_WAITING) elog(PANIC, "queueing for lock while waiting on another one"); LWLockWaitListLock(lock); @@ -1034,10 +1070,11 @@ LWLockQueueSelf(LWLock *lock, LWLockMode mode) pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_HAS_WAITERS); MyProc->lwWaiting = LW_WS_WAITING; - MyProc->lwWaitMode = mode; + MyProc->lwWaitMode = mode & LW_LOCK_MODE_MASK; + MyProc->lwLockRoom = mode & LW_LOCK_ROOM_MASK; /* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */ - if (mode == LW_WAIT_UNTIL_FREE) + if ((mode & LW_LOCK_MODE_MASK) == LW_WAIT_UNTIL_FREE) proclist_push_head(&lock->waiters, MyProcNumber, lwWaitLink); else proclist_push_tail(&lock->waiters, MyProcNumber, lwWaitLink); @@ -1158,13 +1195,15 @@ LWLockAcquire(LWLock *lock, LWLockMode mode) lwstats = get_lwlock_stats_entry(lock); #endif - Assert(mode == LW_SHARED || mode == LW_EXCLUSIVE); - + Assert(mode == LW_SHARED || (mode & LW_LOCK_MODE_MASK) == LW_EXCLUSIVE); + /* assume all rooms on an exclusive lock if omitted */ + if (mode == LW_EXCLUSIVE) + mode |= LW_LOCK_ROOM_MASK; PRINT_LWDEBUG("LWLockAcquire", lock, mode); #ifdef LWLOCK_STATS /* Count lock acquisition attempts */ - if (mode == LW_EXCLUSIVE) + if ((mode & LW_LOCK_MODE_MASK) == LW_EXCLUSIVE) lwstats->ex_acquire_count++; else lwstats->sh_acquire_count++; @@ -1322,7 +1361,11 @@ LWLockConditionalAcquire(LWLock *lock, LWLockMode mode) { bool mustwait; - Assert(mode == LW_SHARED || mode == LW_EXCLUSIVE); + Assert(mode == LW_SHARED || (mode & LW_LOCK_MODE_MASK) == LW_EXCLUSIVE); + + /* assume all rooms on an exclusive lock if omitted */ + if (mode == LW_EXCLUSIVE) + mode |= LW_LOCK_ROOM_MASK; PRINT_LWDEBUG("LWLockConditionalAcquire", lock, mode); @@ -1386,7 +1429,11 @@ LWLockAcquireOrWait(LWLock *lock, LWLockMode mode) lwstats = get_lwlock_stats_entry(lock); #endif - Assert(mode == LW_SHARED || mode == LW_EXCLUSIVE); + Assert(mode == LW_SHARED || (mode & LW_LOCK_MODE_MASK) == LW_EXCLUSIVE); + + /* assume all rooms on an exclusive lock if omitted */ + if (mode == LW_EXCLUSIVE) + mode |= LW_LOCK_ROOM_MASK; PRINT_LWDEBUG("LWLockAcquireOrWait", lock, mode); @@ -1516,7 +1563,7 @@ LWLockConflictsWithVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 oldval, * this, so we don't need a memory barrier here as far as the current * usage is concerned. But that might not be safe in general. */ - mustwait = (pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE) != 0; + mustwait = (pg_atomic_read_u32(&lock->state) & LW_EXCLUSIVE) != 0; if (!mustwait) { @@ -1716,7 +1763,7 @@ LWLockUpdateVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 val) LWLockWaitListLock(lock); - Assert(pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE); + Assert(pg_atomic_read_u32(&lock->state) & LW_EXCLUSIVE); /* * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken @@ -1794,24 +1841,44 @@ LWLockRelease(LWLock *lock) * Release my hold on lock, after that it can immediately be acquired by * others, even if we still have to wakeup other waiters. */ - if (mode == LW_EXCLUSIVE) - oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_EXCLUSIVE); + if ((mode & LW_LOCK_MODE_MASK) == LW_EXCLUSIVE) + { + /* + * Fast path: release the lock without looping if + * - no other holders + * - wait list not locked + * - no waiters + * - no wake in progress + */ + uint32 clear = (mode & LW_LOCK_ROOM_MASK) | LW_EXCLUSIVE; + oldstate = mode | LW_EXCLUSIVE; + while (!pg_atomic_compare_exchange_u32(&lock->state, &oldstate, + oldstate & ~clear)) + { + clear = mode & LW_LOCK_ROOM_MASK; + /* + * Release the exclusive lock if there are no remaining + * locked rooms. + */ + if ((oldstate & ((~mode & LW_LOCK_ROOM_MASK) | LW_FLAG_WAKE_IN_PROGRESS)) == 0) + clear |= LW_EXCLUSIVE; + } + } else - oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_SHARED); - - /* nobody else can have that kind of lock */ - Assert(!(oldstate & LW_VAL_EXCLUSIVE)); + oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_SHARED); if (TRACE_POSTGRESQL_LWLOCK_RELEASE_ENABLED()) TRACE_POSTGRESQL_LWLOCK_RELEASE(T_NAME(lock)); /* * Check if we're still waiting for backends to get scheduled, if so, - * don't wake them up again. + * don't wake them up again. Exclusive room release must wake even + * when other rooms remain; LWLockWakeup filters by waiter rooms. */ if ((oldstate & LW_FLAG_HAS_WAITERS) && !(oldstate & LW_FLAG_WAKE_IN_PROGRESS) && - (oldstate & LW_LOCK_MASK) == 0) + ((oldstate & LW_LOCK_MASK) == 0 || + (mode & LW_LOCK_MODE_MASK) == LW_EXCLUSIVE)) check_waiters = true; else check_waiters = false; @@ -1932,7 +1999,8 @@ LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode) for (i = 0; i < num_held_lwlocks; i++) { - if (held_lwlocks[i].lock == lock && held_lwlocks[i].mode == mode) + if (held_lwlocks[i].lock == lock && + (held_lwlocks[i].mode & LW_LOCK_MODE_MASK) == (mode & LW_LOCK_MODE_MASK)) return true; } return false; diff --git a/src/include/storage/lwlock.h b/src/include/storage/lwlock.h index efa5b427e9f..cdc5195c158 100644 --- a/src/include/storage/lwlock.h +++ b/src/include/storage/lwlock.h @@ -31,7 +31,8 @@ typedef enum LWLockWaitState LW_WS_WAITING, /* currently waiting */ LW_WS_PENDING_WAKEUP, /* removed from waitlist, but not yet * signalled */ -} LWLockWaitState; +} LWLockWaitState; + /* * Code outside of lwlock.c should not manipulate the contents of this @@ -80,8 +81,8 @@ extern PGDLLIMPORT LWLockPadded *MainLWLockArray; */ /* Number of partitions of the shared buffer mapping hashtable */ -#define NUM_BUFFER_PARTITIONS 128 - +#define LOG2_NUM_BUFFER_PARTITIONS 7 +#define NUM_BUFFER_PARTITIONS (1 << LOG2_NUM_BUFFER_PARTITIONS) /* Number of partitions the shared lock tables are divided into */ #define LOG2_NUM_LOCK_PARTITIONS 4 #define NUM_LOCK_PARTITIONS (1 << LOG2_NUM_LOCK_PARTITIONS) @@ -101,14 +102,90 @@ extern PGDLLIMPORT LWLockPadded *MainLWLockArray; typedef enum LWLockMode { - LW_EXCLUSIVE, - LW_SHARED, - LW_WAIT_UNTIL_FREE, /* A special mode used in PGPROC->lwWaitMode, - * when waiting for lock to become free. Not - * to be used as LWLockAcquire argument */ + LW_EXCLUSIVE = 1, + LW_SHARED = 2, + /* A special mode used in PGPROC->lwWaitMode, + * when waiting for lock to become free. Not + * to be used as LWLockAcquire argument */ + LW_WAIT_UNTIL_FREE = 4, + /* For backward compatibility LW_EXCLUSIVE must + * act as LW_EXCLUSIVE + LW_LOCK_ROOM_MASK + */ + /* 16 rooms in two internal bytes */ + LW_LOCK_ROOM_0 = 0x00000100, + LW_LOCK_ROOM_1 = 0x00000200, + LW_LOCK_ROOM_2 = 0x00000400, + LW_LOCK_ROOM_3 = 0x00000800, + LW_LOCK_ROOM_4 = 0x00001000, + LW_LOCK_ROOM_5 = 0x00002000, + LW_LOCK_ROOM_6 = 0x00004000, + LW_LOCK_ROOM_7 = 0x00008000, + + LW_LOCK_ROOM_8 = 0x00010000, + LW_LOCK_ROOM_9 = 0x00020000, + LW_LOCK_ROOM_10 = 0x00040000, + LW_LOCK_ROOM_11 = 0x00080000, + LW_LOCK_ROOM_12 = 0x00100000, + LW_LOCK_ROOM_13 = 0x00200000, + LW_LOCK_ROOM_14 = 0x00400000, + LW_LOCK_ROOM_15 = 0x00800000, + /* + * Alternatively use A-Z, where 5+5 rooms are bits of the + * least and the most significant bytes. + * F-U coincide with 1-15. + */ + LW_LOCK_ROOM_A = 0x00000008, + LW_LOCK_ROOM_B = 0x00000010, + LW_LOCK_ROOM_C = 0x00000020, + LW_LOCK_ROOM_D = 0x00000040, + LW_LOCK_ROOM_E = 0x00000080, + + LW_LOCK_ROOM_F = 0x00000100, + LW_LOCK_ROOM_G = 0x00000200, + LW_LOCK_ROOM_H = 0x00000400, + LW_LOCK_ROOM_I = 0x00000800, + LW_LOCK_ROOM_J = 0x00001000, + LW_LOCK_ROOM_K = 0x00002000, + LW_LOCK_ROOM_L = 0x00004000, + LW_LOCK_ROOM_M = 0x00008000, + + LW_LOCK_ROOM_N = 0x00010000, + LW_LOCK_ROOM_O = 0x00020000, + LW_LOCK_ROOM_P = 0x00040000, + LW_LOCK_ROOM_Q = 0x00080000, + LW_LOCK_ROOM_R = 0x00100000, + LW_LOCK_ROOM_S = 0x00200000, + LW_LOCK_ROOM_T = 0x00400000, + LW_LOCK_ROOM_U = 0x00800000, + + LW_LOCK_ROOM_V = 0x01000000, + LW_LOCK_ROOM_W = 0x02000000, + LW_LOCK_ROOM_X = 0x04000000, + LW_LOCK_ROOM_Y = 0x08000000, + LW_LOCK_ROOM_Z = 0x10000000, + + /* + * 3 high bits reserved for flags in LWLock state + * 3 low bits reserved for modes in LWLockMode + * 26 bits usable as room mask. + */ + LW_LOCK_ROOM_MASK = 0x1ffffff8, + LW_LOCK_MODE_MASK = 0x00000007, } LWLockMode; +/* + * A helper to acquire the lock for one room out of 16 + * LW_EXCLUSIVE + LW_LOCK_ROOM(3) + * LW_EXCLUSIVE + LW_ROOM_3 + */ +#define LW_LOCK_ROOM(i) ((LWLockMode) (1 << (8 + ((i) & 0xF)))) +/* Alternatively one can lock one room out of 26 + * LW_EXCLUSIVE + LW_LOCK_ROOM_ALPHA('A') + * LW_EXCLUSIVE + LW_LOCK_ROOM_ALPHA(12345) + * LW_EXCLUSIVE + LW_LOCK_ROOM_A + */ +#define LW_LOCK_ROOM_ALPHA(i) ((LWLockMode) (1 << (3 + ((i) - 65) % 26))) #ifdef LOCK_DEBUG extern PGDLLIMPORT bool Trace_lwlocks; #endif diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 03a1a466fa8..47232082d61 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -286,6 +286,7 @@ typedef struct PGPROC * is acceptable, although not pretty, because a backend can't wait for * both types of locks at the same time. */ + uint32 lwLockRoom; /* lock room being waited for */ uint8 lwWaiting; /* see LWLockWaitState */ uint8 lwWaitMode; /* lwlock mode being waited for */ proclist_node lwWaitLink; /* position in LW lock wait list */ -- 2.53.0
0002-rooms-applied-to-BufferMapping.patch (application/octet-stream, 5.5K) download From 49da32783fece28aec798a9475e2d7097c340c0b Mon Sep 17 00:00:00 2001 From: Alexandre Felipe <o.alexandre.felipe@gmail.com> Date: Wed, 9 Sep 2026 10:19:22 +0100 Subject: [PATCH 2/2] rooms applied to BufferMapping This commit updates the BufMappingPartitionLock to compute both the partition (selecting a LWLock*) and room, that gives additional granularity for LW_EXCLUSIVE locks. The line LW_LOCK_ROOM_ALPHA(hashcode >> LOG2_NUM_BUFFER_PARTITIONS) doing a `- % + <<` another approach would be `& * >>` sequence. e.g. (hashcode & (0x1f << (32 - 5))) * 26 >> (32 - 5) or with a single 64-bit multiplications as (hashcode * 26ll) >> 32 But we might be about to sleep, that is a bigger concern. --- src/backend/storage/buffer/bufmgr.c | 23 +++++++---------------- src/include/storage/buf_internals.h | 23 ++++++++--------------- 2 files changed, 15 insertions(+), 31 deletions(-) diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c index 17f142e4c5b..b6a0a9130c4 100644 --- a/src/backend/storage/buffer/bufmgr.c +++ b/src/backend/storage/buffer/bufmgr.c @@ -712,10 +712,9 @@ PrefetchSharedBuffer(SMgrRelation smgr_reln, /* determine its hash code and partition lock ID */ newHash = BufTableHashCode(&newTag); - newPartitionLock = BufMappingPartitionLock(newHash); + newPartitionLock = BufMappingPartitionLock(newHash, LW_SHARED); /* see if the block is in the buffer pool already */ - LWLockAcquire(newPartitionLock, LW_SHARED); buf_id = BufTableLookup(&newTag, newHash); LWLockRelease(newPartitionLock); @@ -2217,10 +2216,9 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum, /* determine its hash code and partition lock ID */ newHash = BufTableHashCode(&newTag); - newPartitionLock = BufMappingPartitionLock(newHash); + newPartitionLock = BufMappingPartitionLock(newHash, LW_SHARED); /* see if the block is in the buffer pool already */ - LWLockAcquire(newPartitionLock, LW_SHARED); existing_buf_id = BufTableLookup(&newTag, newHash); if (existing_buf_id >= 0) { @@ -2273,7 +2271,7 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum, * somebody else inserted another buffer for the tag, we'll release the * victim buffer we acquired and use the already inserted one. */ - LWLockAcquire(newPartitionLock, LW_EXCLUSIVE); + newPartitionLock = BufMappingPartitionLock(newHash, LW_EXCLUSIVE); existing_buf_id = BufTableInsert(&newTag, newHash, victim_buf_hdr->buf_id); if (existing_buf_id >= 0) { @@ -2386,15 +2384,13 @@ InvalidateBuffer(BufferDesc *buf) * here? Probably not. */ oldHash = BufTableHashCode(&oldTag); - oldPartitionLock = BufMappingPartitionLock(oldHash); - retry: /* * Acquire exclusive mapping lock in preparation for changing the buffer's * association. */ - LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE); + oldPartitionLock = BufMappingPartitionLock(oldHash, LW_EXCLUSIVE); /* Re-lock the buffer header */ buf_state = LockBufHdr(buf); @@ -2481,9 +2477,7 @@ InvalidateVictimBuffer(BufferDesc *buf_hdr) tag = buf_hdr->tag; hash = BufTableHashCode(&tag); - partition_lock = BufMappingPartitionLock(hash); - - LWLockAcquire(partition_lock, LW_EXCLUSIVE); + partition_lock = BufMappingPartitionLock(hash, LW_EXCLUSIVE); /* lock the buffer header */ buf_state = LockBufHdr(buf_hdr); @@ -2925,9 +2919,7 @@ ExtendBufferedRelShared(BufferManagerRelation bmr, InitBufferTag(&tag, &BMR_GET_SMGR(bmr)->smgr_rlocator.locator, fork, first_block + i); hash = BufTableHashCode(&tag); - partition_lock = BufMappingPartitionLock(hash); - - LWLockAcquire(partition_lock, LW_EXCLUSIVE); + partition_lock = BufMappingPartitionLock(hash, LW_EXCLUSIVE); existing_id = BufTableInsert(&tag, hash, victim_buf_hdr->buf_id); @@ -5094,10 +5086,9 @@ FindAndDropRelationBuffers(RelFileLocator rlocator, ForkNumber forkNum, /* determine its hash code and partition lock ID */ bufHash = BufTableHashCode(&bufTag); - bufPartitionLock = BufMappingPartitionLock(bufHash); + bufPartitionLock = BufMappingPartitionLock(bufHash, LW_SHARED); /* Check that it is in the buffer pool. If not, do nothing. */ - LWLockAcquire(bufPartitionLock, LW_SHARED); buf_id = BufTableLookup(&bufTag, bufHash); LWLockRelease(bufPartitionLock); diff --git a/src/include/storage/buf_internals.h b/src/include/storage/buf_internals.h index e4ff5619b79..e8b0cc72f48 100644 --- a/src/include/storage/buf_internals.h +++ b/src/include/storage/buf_internals.h @@ -242,25 +242,18 @@ BufTagMatchesRelFileLocator(const BufferTag *tag, * The shared buffer mapping table is partitioned to reduce contention. * To determine which partition lock a given tag requires, compute the tag's * hash code with BufTableHashCode(), then apply BufMappingPartitionLock(). - * NB: NUM_BUFFER_PARTITIONS must be a power of 2! + * */ -static inline uint32 -BufTableHashPartition(uint32 hashcode) -{ - return hashcode % NUM_BUFFER_PARTITIONS; -} - -static inline LWLock * -BufMappingPartitionLock(uint32 hashcode) -{ - return &MainLWLockArray[BUFFER_MAPPING_LWLOCK_OFFSET + - BufTableHashPartition(hashcode)].lock; -} static inline LWLock * -BufMappingPartitionLockByIndex(uint32 index) +BufMappingPartitionLock(uint32 hashcode, LWLockMode mode) { - return &MainLWLockArray[BUFFER_MAPPING_LWLOCK_OFFSET + index].lock; + int p = BUFFER_MAPPING_LWLOCK_OFFSET + (hashcode % NUM_BUFFER_PARTITIONS); + LWLock *lock = &MainLWLockArray[p].lock; + if(mode == LW_EXCLUSIVE) + mode += LW_LOCK_ROOM_ALPHA(hashcode >> LOG2_NUM_BUFFER_PARTITIONS); + LWLockAcquire(lock, mode); + return lock; } /* -- 2.53.0
^ permalink raw reply [nested|flat] 13+ messages in thread

* Re: [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer
@ 2026-09-11 09:56  Yuhang Qiu <iamqyh@gmail.com>
  parent: Alexandre Felipe <o.alexandre.felipe@gmail.com>
  0 siblings, 0 replies; 13+ messages in thread

From: Yuhang Qiu @ 2026-09-11 09:56 UTC (permalink / raw)
  To: Alexandre Felipe <o.alexandre.felipe@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Alexandre,

> If this seems acceptable, the next steps could be ...

I don't think this design works.

Rooms change the semantics of an LWLock: exclusive access no longer
excludes all other holders. Data access needs to be reworked to support
this. The buffer mapping access in this patch already has a problem:
different rooms in the same partition can map to the same hash bucket,
allowing concurrent modifications to its chain and causing entries to be
lost.

In 0001, releasing the last room while LW_FLAG_WAKE_IN_PROGRESS is set
leaves LW_EXCLUSIVE set. Shared waiters cannot clear it and remain
blocked forever unless a subsequent exclusive acquisition and release
clears it. This also affects ordinary LW_EXCLUSIVE acquisitions.

All 26 rooms share one state word. Acquirers of disjoint rooms still
CAS on the same cache line, so the scalability bottleneck remains and
may even get worse. In this case, I would increase NUM_BUFFER_PARTITIONS.

Best regards,
Yuhang Qiu







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


end of thread, other threads:[~2026-09-11 09:56 UTC | newest]

Thread overview: 13+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-08-11 18:15 [PATCH] bufmgr: tighten LWLock:BufferMapping on InvalidateBuffer Alexandre Felipe <o.alexandre.felipe@gmail.com>
2026-08-11 18:47 ` Andres Freund <andres@anarazel.de>
2026-08-11 19:32   ` Alexandre Felipe <o.alexandre.felipe@gmail.com>
2026-08-11 20:57     ` Andres Freund <andres@anarazel.de>
2026-08-16 09:54       ` Alexandre Felipe <o.alexandre.felipe@gmail.com>
2026-08-24 07:22         ` Yuhang Qiu <iamqyh@gmail.com>
2026-08-24 08:16           ` Alexandre Felipe <o.alexandre.felipe@gmail.com>
2026-08-24 12:25             ` Andres Freund <andres@anarazel.de>
2026-08-24 21:01               ` Alexandre Felipe <o.alexandre.felipe@gmail.com>
2026-08-25 10:37                 ` Yuhang Qiu <iamqyh@gmail.com>
2026-09-09 09:41                   ` Alexandre Felipe <o.alexandre.felipe@gmail.com>
2026-09-11 09:56                     ` Yuhang Qiu <iamqyh@gmail.com>
2026-08-26 16:01                 ` Andres Freund <andres@anarazel.de>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox