Re: [PATCH RFC 00/33] Compile-time thread-safety checking
From: Marco Elver
Date: Fri Feb 07 2025 - 04:06:38 EST
On Fri, Feb 07, 2025 at 09:42AM +0100, Peter Zijlstra wrote:
> On Thu, Feb 06, 2025 at 10:34:09AM -0800, Bart Van Assche wrote:
>
> > I'm looking forward to the feedback from others about what their opinion
> > is about how to enable thread-safety checking in the Linux kernel.
>
> So Bart's patches are rather SHOUTING A LOT:-(, which I find really
> jarring to look at.
>
> Also, however much I despise the sparse thing, that is something we
> already have some of, so we might as well adapt that.
>
> But I should probably go read up on the whole clang feature first.
>
> I've seen both have a __guarded_by() variant for structure members, can
> you stack those?
>
> Eg. perf has locking where a structure has both a raw_spinlock_t and a
> mutex and modification requires holding both, but holding either is
> sufficient for reading.
Yes, you can add multiple guarded_by. But it's just going to enforce
that you need to hold both locks before you access the member. If you
want the rules to be more complex, the best way to express that is with
some helpers. E.g. something like this (tested on top my series)
--- a/lib/test_capability-analysis.c
+++ b/lib/test_capability-analysis.c
@@ -479,3 +479,53 @@ static void __used test_local_lock_guard(void)
{ guard(local_lock_irqsave)(&test_local_lock_data.lock); this_cpu_add(test_local_lock_data.counter, 1); }
{ guard(local_lock_nested_bh)(&test_local_lock_data.lock); this_cpu_add(test_local_lock_data.counter, 1); }
}
+
+struct some_data {
+ spinlock_t lock;
+ struct mutex mtx;
+ int counter __var_guarded_by(&lock) __var_guarded_by(&mtx);
+};
+
+static void some_data_read_lock_via_lock(struct some_data *d)
+ __acquires(&d->lock) __acquires_shared(&d->mtx)
+{
+ spin_lock(&d->lock);
+ __acquire_shared(&d->mtx);
+}
+
+static void some_data_read_unlock_via_lock(struct some_data *d)
+ __releases(&d->lock) __releases_shared(&d->mtx)
+{
+ __release_shared(&d->mtx);
+ spin_unlock(&d->lock);
+}
+
+static void some_data_read_lock_via_mtx(struct some_data *d)
+ __acquires(&d->mtx) __acquires_shared(&d->lock)
+{
+ mutex_lock(&d->mtx);
+ __acquire_shared(&d->lock);
+}
+
+static void some_data_read_unlock_via_mtx(struct some_data *d)
+ __releases(&d->mtx) __releases_shared(&d->lock)
+{
+ __release_shared(&d->lock);
+ mutex_unlock(&d->mtx);
+}
+
+static void __used foo_1(struct some_data *d)
+{
+ some_data_read_lock_via_lock(d);
+ (void)d->counter;
+ // d->counter++; // error, because mtx only held shared
+ some_data_read_unlock_via_lock(d);
+}
+
+static void __used foo_2(struct some_data *d)
+{
+ some_data_read_lock_via_mtx(d);
+ (void)d->counter;
+ // d->counter++; // error, because lock only held shared
+ some_data_read_unlock_via_mtx(d);
+}