Re: [PATCH] rust: add `CacheAligned` for easy cache line alignment of values
From: Andreas Hindborg
Date: Tue May 19 2026 - 05:29:23 EST
"Gary Guo" <gary@xxxxxxxxxxx> writes:
> On Wed Jan 28, 2026 at 2:05 PM GMT, Andreas Hindborg wrote:
>> `CacheAligned` allows to easily align values to a 64 byte boundary.
>>
>> An example use case is the kernel `struct spinlock`. This struct is 4 bytes
>> on x86 when lockdep is not enabled. The structure is not padded to fit a
>> cache line. The effect of this for `SpinLock` is that the lock variable and
>> the value protected by the lock might share a cache line, depending on the
>> alignment requirements of the protected value. Wrapping the value in
>> `CacheAligned` to get a `SpinLock<CacheAligned<T>>` solves this problem.
>
> Do you mean `CacheAligned<SpinLock<T>>`?
>
I missed this in my original reply.
I mean `SpinLock<CacheAligned<T>>` as I wrote. The `SpinLock` will be
aligned to some alignment, possibly the start of a cache line. Taking
the lock involves getting exclusive ownership of the cache line and
updating the lock state. When the lock is contended, the CPU core that
takes the lock will loose exclusive ownership of the cache line
immediately after taking the lock, as other CPU cores are trying to take
the lock.
The logical thing to do after taking a lock is looking at the value
protected by the lock. As the winning CPU tries to do this, it has to
obtain ownership of the cache line again, assuming the `T` lives on the
same cache line as the lock state. If we align the `T` to a cache line,
then that line will not be contended. Only the cache line holding the
lock state will be contended. And then observing the T does not incur
the overhead obtaining a highly contended cache line.
Best regards,
Andreas Hindborg