Re: [PATCH v3] rust: add global lock support
From: Benno Lossin
Date: Fri Sep 13 2024 - 12:52:19 EST
On 13.09.24 18:10, Alice Ryhl wrote:
> On Fri, Sep 13, 2024 at 6:02 PM Simona Vetter <simona.vetter@xxxxxxxx> wrote:
>> On Tue, Sep 10, 2024 at 02:23:34PM +0000, Alice Ryhl wrote:
>>> Add support for creating global variables that are wrapped in a mutex or
>>> spinlock. Optionally, the macro can generate a special LockedBy type
>>> that does not require a runtime check.
>>>
>>> The implementation here is intended to replace the global mutex
>>> workaround found in the Rust Binder RFC [1]. In both cases, the global
>>> lock must be initialized before first use. The macro is unsafe to use
>>> for the same reason.
>>>
>>> The separate initialization step is required because bindgen refuses to
>>> expose __ARCH_SPIN_LOCK_UNLOCKED to Rust as a compile-time constant. It
>>> just generates an `extern "C"` global reference instead. In the future,
>>> we could expose the value of __ARCH_SPIN_LOCK_UNLOCKED to Rust in a way
>>> that Rust can understand. This would remove the need for a separate
>>> initialization step.
>>
>> Yeah it's just a raw C struct initializer, I wouldn't even know how to
>> move that to rust.
>>
>> An absolute horrible idea, and I didn't try whether it's even possible:
>> - put all the global locks of a type into a special linker section (we
>> need a macro anyway for them).
>> - patch them up with a horrible linker script objtool patching with an
>> example lock initialized by the C macro.
>>
>> Even worse idea, on most architectures/config it's all zeros. Iirc the one
>> I've found that might matter a bit is CONFIG_SMP=n with some lock
>> debugging enabled. We could make rust support conditional on those, and
>> then maybe a build-time check that it's actually all set to 0 ...
>>
>> Requiring the unsafe init just feels a bit disappointing to me, when the C
>> side (including lockdep annotations) tries really hard to make global
>> locks a one-liner.
>
> I actually have a prototype lying around that gets rid of the
> initialization step. The idea is to define some new macros:
>
> #define __ARCH_SPIN_LOCK_UNLOCKED { 0 }
> +#define __ARCH_SPIN_LOCK_UNLOCKED_TYP unsigned int
> +#define __ARCH_SPIN_LOCK_UNLOCKED_INT 0
>
> Rust then uses the two new #defines to initialize the raw spin lock to
> the right bytes. As long as __ARCH_SPIN_LOCK_UNLOCKED and
> __ARCH_SPIN_LOCK_UNLOCKED_INT are represented by the same sequence of
> bytes, it should work.
I have no idea if this is possible, but maybe one of the C experts can
help with this: could we define `__ARCH_SPIN_LOCK_UNLOCKED` in terms of
`__ARCH_SPIN_LOCK_UNLOCKED_INT`? That way there is only one source of
truth.
---
Cheers,
Benno