Re: Detect double-release of spinlock - Mailing list pgsql-hackers

From Andres Freund
Subject Re: Detect double-release of spinlock
Date
Msg-id 20240729182952.hua325647e2ggbsy@awork3.anarazel.de
Whole thread Raw
In response to Re: Detect double-release of spinlock  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-hackers
Hi,

Partially replying here to an email on -committers [1].

On 2024-07-29 13:57:02 -0400, Tom Lane wrote:
> Andres Freund <andres@anarazel.de> writes:
> > However, I still don't think it's a problem to assert that the lock is held in
> > in the unlock "routine". As mentioned before, the spinlock implementation
> > itself has never followed the "just straight line code" rule that users of
> > spinlocks are supposed to follow.
>
> Yeah, that's fair.

Cool.


On 2024-07-29 13:56:05 -0400, Tom Lane wrote:
> Andres Freund <andres@anarazel.de> writes:
> > b) Instead define the spinlock to have 1 as the unlocked state and 0 as the
> >    locked state. That makes it a bit harder to understand that initialization
> >    is missing, compared to a dedicated state, as the first use of the spinlock
> >    just blocks.
>
> This option works for me.

> > To make 1) b) easier to understand it might be worth changing the slock_t
> > typedef to be something like
>
> > typedef struct slock_t
> > {
> >         char is_free;
> > } slock_t;
>
> +1

Cool. I've attached a prototype.


I just realized there's a nice little advantage to the "inverted"
representation - it detects missing initialization even in optimized builds.


> How much of this would we change across platforms, and how much
> would be x86-only?  I think there are enough people developing on
> ARM (e.g. Mac) now to make it worth covering that, but maybe we
> don't care so much about anything else.

Not sure. Right now I've only hacked up x86-64 (not even touching i386), but
it shouldn't be hard to change at least some additional platforms.

My current prototype requires S_UNLOCK, S_LOCK_FREE, S_INIT_LOCK to be
implemented for x86-64 instead of using the "generic" implementation. That'd
be mildly annoying duplication if we did so for a few more platforms.


It'd be more palatable to just change all platforms if we made more of them
use __sync_lock_test_and_set (or some other intrinsic(s))...

Greetings,

Andres Freund

[1] https://postgr.es/m/2812376.1722275765%40sss.pgh.pa.us

Attachment

pgsql-hackers by date:

Previous
From: Andres Freund
Date:
Subject: Re: Detect double-release of spinlock
Next
From: Robert Haas
Date:
Subject: 040_pg_createsubscriber.pl is slow and unstable (was Re: speed up a logical replica setup)