Re: [RFC PATCH 1/2] rust: add initial scatterlist bindings

From: Daniel Almeida
Date: Fri May 16 2025 - 13:03:01 EST


Hi Danilo,

Replying to you and Lyude here at the same time.

> On 15 May 2025, at 18:11, Danilo Krummrich <dakr@xxxxxxxxxx> wrote:
>
> On Mon, May 12, 2025 at 08:39:36AM -0300, Daniel Almeida wrote:
>>> On 12 May 2025, at 06:53, Abdiel Janulgue <abdiel.janulgue@xxxxxxxxx> wrote:
>>> +impl SGEntry {
>>> + /// Convert a raw `struct scatterlist *` to a `&'a SGEntry`.
>>> + ///
>>> + /// # Safety
>>> + ///
>>> + /// Callers must ensure that the `struct scatterlist` pointed to by `ptr` is valid for the lifetime
>>> + /// of the returned reference.
>>> + pub unsafe fn as_ref<'a>(ptr: *mut bindings::scatterlist) -> &'a Self {
>>> + // SAFETY: The pointer is valid and guaranteed by the safety requirements of the function.
>>> + unsafe { &*ptr.cast() }
>>> + }
>>
>> Hmm, this name is not good. When people see as_ref() they will think of the
>> standard library where it is used to convert from &T to &U. This is not what is
>> happening here. Same in other places where as_ref() is used in this patch.
>
> as_ref() is fine, we use this exact way commonly in the kernel, e.g. for Device,
> GlobalLockedBy, Cpumask and for various DRM types.
>
> Rust std does the same, e.g. in [1].
>
> I think I also asked for this in your Resource patch for consistency, where you
> call this from_ptr() instead.
>
> [1] https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_ref
>

That is not the same thing. What you've linked to still takes &self and returns
&T. In order words, it converts *from* &self to another type:

pub trait AsRef<T>
where
T: ?Sized,
{
// Required method
fn as_ref(&self) -> &T;
}

The signature in the kernel is different, i.e.:

fn as_ref<'a>(ptr: *mut bindings::scatterlist) -> &'a Self

This takes a pointer and converts *to* &self, which is a bit in the wrong
direction IMHO. You also have to provide `ptr`, which is a departure from the
syntax used elsewhere in Rust, i.e.:

// no explicit arguments:
let bar: &Bar = foo.as_ref();

vs

// slightly confusing:
//
// Bar::as_ref() creates &Bar instead of taking it as an argument to return something else
let bar = Bar::as_ref(foo_ptr);


Which is more akin to how the "from" prefix works, starting from the From trait
itself, i.e.:

let bar = Bar::from(...); // Ok: creates Bar,

...to other similar nomenclatures:

let bar = Bar::from_ptr(foo_ptr); // Ok, creates &Bar

So, IMHO, the problem is not conflicting with the std AsRef, in the sense that the
code might not compile because of it. The problem is taking a very well
known name and then changing its semantics.

Anyways, this is just a small observation. I'll drop my case, specially
considering that the current as_ref() is already prevalent in a lot of code upstream :)

— Daniel