Re: [PATCH RFC 0/2] rust: sync: create lock class using `#[track_caller]`
From: Peter Zijlstra
Date: Fri Jul 03 2026 - 18:33:14 EST
On Fri, Jul 03, 2026 at 03:24:29PM +0100, Gary Guo wrote:
> On Fri Jul 3, 2026 at 3:01 PM BST, Peter Zijlstra wrote:
> > On Fri, Jul 03, 2026 at 02:47:25PM +0100, Gary Guo wrote:
> >> Currently we're adding more and more macros so that lock classes can be
> >> created. The only purpose served by these macros are to create names and
> >> static lock classes so they can be tracked by lockdep.
> >>
> >> I've come up with an approach that uses `Location::caller` and Rust's
> >> `#[track_caller]` feature for this purpose instead. `Location::caller()`
> >> will return a `&'static Location<'static>` that lives in `.rodata`. As
> >> only addresses matter for static objects, the address of the `Location`
> >> themselves could be used for lock classes. The `Location` is of 2 * usize +
> >> 8 bytes, so they could host 2 lock class keys, so `DelayedWork` which needs
> >> two lock classes can also use this mechanism.
> >>
> >> The `Location::caller` could also be used to provide the name; currently,
> >> `optional_name` just uses `file_name:line_number` as the name, and this
> >> information is available in `Location`. However, `Location` encodes them
> >> using file name as a C string plus two `u32`'s for line and column number,
> >> so it cannot provide a single name. I came up with an alternative method,
> >> which is to use a special string, which lockdep can recognize and delegate
> >> back to Rust to print it.
> >
> > Perhaps add some sample output so us simple folk that still think rust
> > looks like line noise can have an idea of what it'll look like. Because
> > I just cannot make much sense of the above.
>
> The above is mostly about the Rust implementation detail. On the lockdep side,
> essentially the name will be "(rust)", while the actual name can be retrieved
> from the lock class key.
>
> So for
>
> let foo = KBox::pin_init(Mutex::new(42));
>
> in, say, foo.c:123
>
> it will eventually call
>
> struct rust_location *loc = /* static generated by the Rust compiler */;
> mutex_init_lockdep(foo, "(rust)", (struct lock_class_key *)loc)
>
> And when "(rust)" is encountered as lock class name, instead of printing the
> string as is, lockdep will call
>
> lockdep_print_rust_name(loc)
>
> which will be doing essentially
>
> pr_cont("foo.c:123");
That seems quite terrible. The C names are based on the expression used
to initialize the class and are thus somewhat descriptive. But file:line
combos are horrid identifiers for locks.
Why would you want to do this?